简体   繁体   English

当所有属性都存在时如何解决属性错误?

[英]how to solve attribute error when all attributes do exist?

I am writing a program for my A level course in python and i need to access an attribute from one class in to another using inheritance. 我正在用python编写A级课程的程序,我需要使用继承从一个类访问另一个类的属性。 here is an example of what I am trying to do. 这是我正在尝试做的一个例子。

class class1():
    def __init__(self):
        self.testValue = 'hello'

class class2(class1):
    def __init__(self):
        self.inheritedValue = class1.testValue
        print(self.inheritedValue)



object = class2()

when running this code i get the following attribute error. 运行此代码时,出现以下属性错误。

AttributeError: type object 'class1' has no attribute 'testValue' AttributeError:类型对象“ class1”没有属性“ testValue”

anyone got a solution for this?? 有人为此解决了吗?

First a comment to code style: class names are written in CamelCase, so name them Class1 and Class2. 首先对代码样式进行注释:类名是用CamelCase编写的,因此将它们命名为Class1和Class2。

Secondly, your class Class1 doesn't have the said attribute, but each instance does. 其次,您的Class1 没有上述属性,但是每个实例都有。

So your class2 should look like 所以你的class2应该看起来像

class Class2(Class1):
    def __init__(self):
        super().__init__() # now we have everything Class1 provides us with
        self.inheritedValue = self.testValue
        print(self.inheritedValue)

because each object of Class2 is also an object of Class1 因为Class2的每个对象也是Class1的对象

The attribute does not exist within the scope of class2 the way you've implemented it. 在您实现该属性的方式下,该属性不存在于class2的范围内。 By passing it in the class definition, it is inherited but the attribute doesn't exist yet. 通过在类定义中传递它,可以继承它,但该属性尚不存在。 That is, unless you've called the constructor. 也就是说,除非您已调用构造函数。 Two ways of doing this, by either using the super built-in function(not recommended in real life, see here , it's a nice read. Anyway, here are a few solutions: 有两种方法可以使用super内置函数(在现实生活中不建议使用,请参阅此处 ,这是一本不错的书。无论如何,这里有一些解决方案:

class class1():
    def __init__(self):
        self.testValue = 'hello'

class class2(class1):
    def __init__(self):
        class1.__init__(self)        
        print(self.testValue)



obj = class2()

if you do not want to call the constructor of the class you are inheriting, you could do something like this: 如果不想调用要继承的类的构造函数,则可以执行以下操作:

class class1():
    testValue = 'hello'
    def __init__(self):
        pass

class class2(class1):
    def __init__(self):
        self.inheritedValue = class1.testValue
        print(self.inheritedValue)

obj = class2()

Side note, object is a built-in so you shouldn't use it. 旁注, object是内置的,因此您不应使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM