【问题标题】:Can't access attributes in python [duplicate]无法访问python中的属性[重复]
【发布时间】:2018-05-15 10:44:03
【问题描述】:

当我运行这段代码时,我得到一个错误“AttributeError: 'NoneType' object has no attribute 'test'”

class BaseClass:
    def __new__(self, number):
        self.test = 1

class InheritedClass(BaseClass):
    pass

instance = InheritedClass(1)
print(instance.test)

有人可以向我解释一下到底从基础继承了什么吗? Python 2 和 3 之间似乎存在差异,因为如果我将“test”放在 Baseclass 的属性字段中,我可以在 Python 2 中访问它,但不能在 3 中访问它。

【问题讨论】:

  • 我认为重复的答案中没有讨论过这个问题。 Python 2 和 3 之间的行为差​​异在于 __new__() 仅存在于新式类,即那些显式继承自 object 的类。在您的代码中,__new__() 在 Python 2 中甚至没有被调用。在 Python 3 中它被调用,但没有实例,因为 __new__() 返回 None - __new__() 应该返回实例。副本中的答案更详细地解决了后一点。

标签: python python-3.x inheritance class-visibility


【解决方案1】:

尝试将“new”替换为“init

class BaseClass:
    def __init__(self, number):
        self.test = 1

class InheritedClass(BaseClass):
    pass

instance = InheritedClass(1)
print(instance.test)

【讨论】:

  • OP 正在寻求解释,而不仅仅是有效的代码。
【解决方案2】:

newinit 之间存在区别。 要访问这样的字段,您应该在 init 中调用它们。

【讨论】:

  • OP 正在寻求解释,而不仅仅是有效的代码。
猜你喜欢
  • 2020-04-23
  • 2013-03-20
  • 2011-11-05
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2014-09-19
  • 1970-01-01
相关资源
最近更新 更多