我有一个永远不会被实例化的基类.这个基类有不同的子类.每个子类定义某些类变量,其中所有子类的名称相同,但值将不同.例如
class Base:
def display(self):
print self.logfile, self.loglevel
class d1(Base):
logfile = "d1.log"
loglevel = "debug"
def temp(self):
Base.display(self)
class d2(Base):
logfile = "d2.log"
loglevel = "info"
def temp(self):
Base.display(self)
Run Code Online (Sandbox Code Playgroud)
设计这个的正确方法是什么,以便我可以强制执行,如果明天定义任何新的子类,实现子类的人应该为这些类变量提供一些值而不是错过定义它们?
And*_*org 10
一个不需要实例化类以进行检查的替代方法是创建一个元类:
class BaseAttrEnforcer(type):
def __init__(cls, name, bases, d):
if 'loglevel' not in d:
raise ValueError("Class %s doesn't define loglevel attribute" % name)
type.__init__(cls, name, bases, d)
class Base(object):
__metaclass__ = BaseAttrEnforcer
loglevel = None
class d1(Base):
logfile = "d1.log"
loglevel = "debug"
class d2(Base):
logfile = "d2.log"
loglevel = "info"
class d3(Base):
logfile = "d3.log"
# I should fail
Run Code Online (Sandbox Code Playgroud)
这应该工作
>>> class Base(object):
... def __init__(self):
... if not hasattr(self, "logfile"):
... raise Exception("not implemented")
...
>>> class d1(Base):
... logfile='logfile1.log'
...
>>> class d2(Base):
... pass
...
>>> d1()
<__main__.d1 object at 0x7d0d0>
>>> d2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
not implemented
Run Code Online (Sandbox Code Playgroud)
您可以使用ciphor建议的构造函数中的简单检查来完成此操作,但您也可以在基类中使用abc.abstractproperty装饰器来确保定义类似于您想要的属性.
然后解释器将检查实例化实例时是否创建了日志文件:
import abc
#It is almost always a good idea to have your base class inherit from object
class Base(object):
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def logfile(self):
raise RuntimeError("This should never happen")
class Nice(Base):
@property
def logfile(self):
return "actual_file.log"
class Naughty(Base):
pass
d=Nice() #This is fine
print d.logfile #Prints actual_file.log
d=Naughty() #This raises an error:
#TypeError: Can't instantiate abstract class Base with abstract methods logfile
Run Code Online (Sandbox Code Playgroud)
有关 详细信息,请参阅 http://docs.python.org/library/abc.html ,可能更有用:http: //www.doughellmann.com/PyMOTW/abc/.
还有一点需要注意 - 当您的子类在原始示例中调用Base.display(self)时,让它们调用self.display()会更有意义.该方法继承自base,这样就避免了对基类进行硬编码.如果你有更多的子类,那么它也会使继承链变得更清晰.