super()是不是要用于staticmethods?
当我尝试类似的东西
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
l = super(Second).getlist()
l.append('second')
return l
a = Second.getlist()
print a
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Traceback (most recent call last):
File "asdf.py", line 13, in <module>
a = Second.getlist()
File "asdf.py", line 9, in getlist
l = super(Second).getlist()
AttributeError: 'super' object has no attribute 'getlist'
Run Code Online (Sandbox Code Playgroud)
如果我将staticmethods更改为classmethods并将类实例传递给super(),那么一切正常.我在这里不正确地调用超级(类型)还是有些东西我不见了?
我正在写一个元类,不小心这样做:
class MetaCls(type):
def __new__(cls, name, bases, dict):
return type(name, bases, dict)
Run Code Online (Sandbox Code Playgroud)
......而不是像这样:
class MetaCls(type):
def __new__(cls, name, bases, dict):
return type.__new__(cls, name, bases, dict)
Run Code Online (Sandbox Code Playgroud)
这两个元类之间究竟有什么区别?更具体地说,导致第一个不能正常工作的原因(某些类没有被元类调用)?
class Meta(type):
def __new__(cls, name, bases, dct):
new_class = type(name, bases, dct)
new_class.attr = 100 # add some to class
return new_class
class WithAttr(metaclass=Meta):
pass
print(type(WithAttr))
# <class 'type'>
Run Code Online (Sandbox Code Playgroud)
为什么它打印<class 'type'>,但不<class '__main__.Meta'>
打印我对吗,类 WithAttr 是 Meta 的实例?