为什么Python设计者决定子类的__init__()方法不会__init__()像其他语言那样自动调用超类的方法?Pythonic和推荐的成语是否真的如下?
class Superclass(object):
def __init__(self):
print 'Do something'
class Subclass(Superclass):
def __init__(self):
super(Subclass, self).__init__()
print 'Do something else'
Run Code Online (Sandbox Code Playgroud) 我正在阅读'Dive Into Python',并在关于类的章节中给出了这个例子:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
Run Code Online (Sandbox Code Playgroud)
然后,作者说如果要覆盖该__init__方法,则必须__init__使用正确的参数显式调用父级.
FileInfo班有一个以上的祖先课怎么办?
__init__方法? 使用类定义装饰器时,如何自动转移__name__,__module__和__doc__?通常,我会使用functools的@wraps装饰器.这是我为一个课而做的(这不完全是我的代码):
class memoized:
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
super().__init__()
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncacheable -- for instance, passing a list as an argument.
# Better to not …Run Code Online (Sandbox Code Playgroud) 我阅读了这个问题评分最高的答案,它说__init__如果需要,我们应该打电话给超级班,而我们不必这样做。但我的问题更多的是关于约定。
通常,作为一般规则,我是否应该始终__init__在我的类中调用超类__init__,而不管我目前是否“需要”该方法中的功能?
有人可以解释我以下代码TickGenerator继承Observer的对象和方法,为什么我们需要observer.init?
class TickGenerator(Observer):
def __init__(self):
Observer.__init__(self)
self.price = 1000
Run Code Online (Sandbox Code Playgroud) python ×5
superclass ×2
class ×1
convention ×1
decorator ×1
delegation ×1
inheritance ×1
overriding ×1
subclass ×1