Python 定义或自动设置类类型的必填字段
我有一系列派生类“ChildA”、“ChildB”等。。。都从基类“父”继承 父类的目的是实现一个在子类中执行代码的通用方法。此方法中有一个基于子实例“状态”的条件Python 定义或自动设置类类型的必填字段,python,class,oop,abstract-class,subclass,Python,Class,Oop,Abstract Class,Subclass,我有一系列派生类“ChildA”、“ChildB”等。。。都从基类“父”继承 父类的目的是实现一个在子类中执行代码的通用方法。此方法中有一个基于子实例“状态”的条件 class Parent: def process(self): try: self.run() except: assert self.status == 'ok' class ChildA(Parent): def run(self
class Parent:
def process(self):
try:
self.run()
except:
assert self.status == 'ok'
class ChildA(Parent):
def run(self):
...
我想把未来的开发人员的子类从令人不快的意外中拯救出来
我觉得解决方案将以抽象类的形式出现,但我还没有(完全)掌握这个概念。或者更确切地说,我了解这个概念,但不知道如何应用它
否则,我可以:
- 指定对文档中“状态”字段的要求。
- 我更喜欢一种严格而有机的执法手段
- 将
添加到父类,并要求(再次通过文档)使用所有子类 super()调用父函数的init函数。\uuuu init\uuuuu(self):self.status=None
- 对于一个只初始化一个字段的基本init方法来说,看起来过于复杂了,但是如果这是python的方式,那么愿意使用它
- 检查Parent.process()开头的.status字段
- 这项工作只做一行,但太粗糙了
运行Python3.5我认为显式和调用super可能是最好的方法。 但是您也可以考虑使用父类中的属性:
class Parent(object):
def process(self):
try:
self.run()
except Exception, e:
assert self.status == 'ok'
def get_status(self):
try:
return self._status
except AttributeError:
print "oops: child class did not initialize status"
return "ok"
def set_status(self, status):
self._status = status
status = property(get_status, set_status)
class BadChild(Parent):
def run(self):
print "run bad"
self.status
class GoodChild(Parent):
def __init__(self):
self.status = "ok"
def run(self):
print "run good"
self.status
以及测试:
bad = BadChild()
good = GoodChild()
good.process()
bad.process()
我认为直言不讳地打电话给super可能是最好的方式。 但是您也可以考虑使用父类中的属性:
class Parent(object):
def process(self):
try:
self.run()
except Exception, e:
assert self.status == 'ok'
def get_status(self):
try:
return self._status
except AttributeError:
print "oops: child class did not initialize status"
return "ok"
def set_status(self, status):
self._status = status
status = property(get_status, set_status)
class BadChild(Parent):
def run(self):
print "run bad"
self.status
class GoodChild(Parent):
def __init__(self):
self.status = "ok"
def run(self):
print "run good"
self.status
以及测试:
bad = BadChild()
good = GoodChild()
good.process()
bad.process()
“权利”解决方案始终取决于具体的用例和目标受众——但在所有情况下,您都希望清楚地记录您的API以及子类的期望值。有一点非常错误,即使用了未区分的
except
子句:始终指定您期望的错误,或者至少记录您得到的错误。Worth注意!实际的代码行是,除了(keyrerror,indexer)为e:
“right”解决方案始终取决于具体的用例和目标受众——但在所有情况下,您都希望清楚地记录您的API以及子类的期望值。有一点非常错误,即使用了未区分的except
子句:始终指定您期望的错误,或者至少记录您得到的错误。Worth注意!实际的代码行是,除了(KeyError,Indexer)为e:
。