首页 > 解决方案 > AttributeError:“str”对象没有属性“describe”

问题描述

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()

标签: python-3.xclassattributeerror

解决方案


Computer_1Computer_2并且Computer_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()

推荐阅读