社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何修复Python错误:attribute error:type object X没有属性Y

ee94jrlc • 5 年前 • 1632 次点击  

我正在创建一个practice python文件,以便更好地理解面向对象编程,我得到以下错误:

AttributeError: type object 'ID' has no attribute 'the_other_number'

我真的不明白为什么会发生这种情况,因为当我像下面这样改变变量时,它工作得很好。我只在尝试在if语句中使用它时收到错误:

ID.the_other_number = 'new_value'

下面是我的示例代码,我正在试图修复,任何帮助都是感激的。

class ID():
   def __init__(self):
       self.other_number()
       pass

   def other_number(self):
       self.the_other_number = 3111

class ID_2():
    def __init__(self):
        self.update_number()

    def update_number(self):
       if ID.the_other_number > 4:
           print(ID.the_other_number)

if __name__ == '__main__':
   ID()
   ID_2()

我希望它能理解什么变量等于并正确运行if语句。另外,不要试图理解代码,我意识到代码没有意义,它只是一个例子。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51708
 
1632 次点击  
文章 [ 3 ]  |  最新文章 5 年前
BoboDarph
Reply   •   1 楼
BoboDarph    6 年前

@Patrick Haugh的回答已经解释了为什么你的代码不能按照你期望的方式执行。 如果不存在缩进问题,我将修改您的代码以打印类ID的“其他”number属性:

class ID():
    def __init__(self):
        self.other_number()

    def other_number(self):
        self.the_other_number = 3111
        return self.the_other_number

class ID_2():
    def __init__(self):
        self.update_number()

    def update_number(self):
        id = ID()
        if id.other_number() > 4:
            print(id.the_other_number)

if __name__ == '__main__':
   ID()
   ID_2()
ThePerson
Reply   •   2 楼
ThePerson    6 年前

你犯了一个错误:你必须明白 ID 是类,不是对象

所以,如果你想使用函数 ID.the_other_number ,必须首先创建 身份证件 . 所以,只需在代码中添加一行代码

class ID():
   def __init__(self):
       self.other_number()
       pass

   def other_number(self):
       self.the_other_number = 3111

class ID_2():
    def __init__(self):
        self.update_number()

    def update_number(self):

        # Create one object of class ID - ID_object
        ID_object = ID()

        # Call the function for ID_object
        if ID_object.the_other_number > 4:
           print(ID_object.the_other_number)

if __name__ == '__main__':
   ID()
   ID_2()
Patrick Haugh
Reply   •   3 楼
Patrick Haugh    6 年前

当你跑的时候 ID() 的新实例 ID 类已创建。 __init__ 打电话给 other_number 该实例的方法,该方法指定实例属性 the_other_number . 因为您不在任何地方保存该实例,所以通过指定 ID() ,立即收集垃圾。这个 身份证件 类不变。

当你跑的时候 ID_2() ,您将创建 ID_2 上课和跑步 __初始__ 方法。这就叫 update_number 方法,它检查 ID._the_other_number . 身份证件 没有 对方号码 属性,因此引发错误。

阅读 Python tutorial on Classes ,并特别注意类对象和实例对象之间的区别。