相关疑难解决方法(0)

super()和@staticmethod交互

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(),那么一切正常.我在这里不正确地调用超级(类型)还是有些东西我不见了?

python static-methods super python-2.7

42
推荐指数
2
解决办法
1万
查看次数

python中类型和类型.__ new__有什么区别?

我正在写一个元类,不小心这样做:

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)

这两个元类之间究竟有什么区别?更具体地说,导致第一个不能正常工作的原因(某些类没有被元类调用)?

python types metaclass new-operator

15
推荐指数
5
解决办法
5763
查看次数

类/类的类型,使用元类创建

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 的实例?

python oop metaclass python-3.x

3
推荐指数
1
解决办法
61
查看次数