【发布时间】:2016-06-13 01:35:36
【问题描述】:
logging.Logger 的文档指出:
请注意,Logger 永远不会直接实例化,而是始终通过模块级函数 logging.getLogger(name)
这让我想到了以下问题(我将切换到一些Foo 类而不是logging.Logger,因为我想问一下一般的原理)。
假设有一些类Foo,有几个属性和方法:
class Foo:
def method_0(self..):
...
def method_1(self..):
...
def method_n(self..):
...
我想继承Foo,并且只专门化其中的几个方法。
class SubFoo(Foo):
def method_1(self, ...):
...
# Or super - not the point of the question.
Foo.method_1(self, ...)
...
问题在于Foo 没有可用的构造函数,只有创建Foo 类型对象的方法,例如通过getFoo。 SubFoo 的“Foo”部分需要是“已批准”Foo 对象,我不知道如何强制将 SubFoos Foo 部分设为“已批准”对象。
注意
对于Foo 的子类化显然有几个解决方法,例如,组合、猴子修补、与__dict__/gettatr 的巧妙游戏等。尽管如此,这个问题是关于子类化的。
【问题讨论】:
-
你应该使用
__new__方法在__init__之前构造子类。我发现docs.scipy.org/doc/numpy/user/… 非常有用。
标签: python inheritance constructor