【问题标题】:AttributeError: 'str' object has no attribute 'describe' [closed]AttributeError:'str'对象没有属性'describe'[关闭]
【发布时间】:2021-08-27 12:29:15
【问题描述】:
class Computer:

    def _inti_(self, storage, color , system):
        no_of_Computer = 0
        self.storage = storage
        self.color = color
        self.system = system
        Computer.no_of_Computer +=1

    def describe (self):

        print(f'my storage is {self.storage} and my color is{self.color} and my system is {self.system}')

Computer_1 = ("1TB ,  silver , windows ")

Computer_2 = (" 4TB , black , linux")

Computer_3 = (" 9TB , white ,mac ")

Computer_1.describe()

【问题讨论】:

  • 问题是什么?
  • 首先,正确启动类,使用__init__再试一次

标签: python-3.x class attributeerror


【解决方案1】:

Computer_1Computer_2Computer_3 不是 Computer 实例,它们只是字符串(用括号括起来)。您需要调用Compueter 的构造函数来创建它的新实例。另外,请注意每个参数应该是它自己的字符串,而不是一个带有逗号的字符串。 此外,请注意构造函数是由方法 __init__ 定义的(注意双取消划线),而不是 _inti_

class Computer:

    def __init__(self, storage, color , system):
        no_of_Computer = 0
        self.storage = storage
        self.color = color
        self.system = system
        Computer.no_of_Computer +=1

    def describe (self):

        print(f'my storage is {self.storage} and my color is{self.color} and my system is {self.system}')

Computer_1 = Computer("1TB", "silver", "windows")

Computer_2 = Computer("4TB", "black", "linux")

Computer_3 = Computer("9TB", "white", "mac")

Computer_1.describe()

【讨论】:

  • 我认为no_of_Computer = 0应该在__init__之外
  • @diggusbickus 你可能是对的,但对 this 问题无关紧要,所以我只是从 OP 的代码中照原样复制它。
猜你喜欢
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
相关资源
最近更新 更多