无法访问 python 中的属性



当我运行此代码时,我会收到一个错误" attributeError:'nontype'对象没有属性'test'"

class BaseClass:
    def __new__(self, number):
        self.test = 1
class InheritedClass(BaseClass):
    pass
instance = InheritedClass(1)
print(instance.test)

有人可以向我解释什么是从基地那里继承了什么?Python 2和3之间似乎存在差异,因为如果我将"测试"放在基本属性的属性字段中,则可以在Python 2中访问它,但在3。

中却不能访问它。

尝试替换" new "到" init "

class BaseClass:
    def __init__(self, number):
        self.test = 1
class InheritedClass(BaseClass):
    pass
instance = InheritedClass(1)
print(instance.test)

new init 之间存在差异。要访问这样的字段,您应该在Init中称呼它们。

最新更新