【问题标题】:I am getting "AttributeError: 'str' object has no attribute我收到“AttributeError:‘str’对象没有属性
【发布时间】:2020-12-19 23:24:18
【问题描述】:

我在第 26 行收到“AttributeError: 'str' object has no attribute 'model'”。我不知道为什么?不知道如何改正?

 import time
 import threading 
                
    def test(name,name2):
        print(name)
        print(name2)
        car.show(name)
        car.color(name2)
        time.sleep(30) 
            
class car(): 
    def __init__(self, model, color): 
        self.model = model 
        self.color = color 
                  
def show(self): 
    print("Model is", self.model ) 
    print("color is", self.color ) 
                  
    audi = car("audi a4", "blue")
    ferrari = car("ferrari 488", "green") 
    acura = car("acura" , "black")
    BMW = car("BMW" , "blue")
    Cadillac  = car("Cadillac", "green")  
        
    f = open("/home/stuff/script/QT/car.txt", "r") #In car.txt file has car model and color list line by line
        
    threads = []  
    for x in range (5):
    name=(f.readline())
    name=name.strip()
    name2=(f.readline())
    name2=name2.strip()                              
    info = threading.Thread (target=test(name,name2))
    threads.append(info)
    info.start()
                        
    x= +x;
                      
    f.close()

【问题讨论】:

  • 您需要使用正确的缩进正确地格式化您的代码。此外,提供完整的堆栈跟踪(完整的错误消息)。您还需要提供minimal reproducible example。目前您的代码中有很多似乎没有被使用。
  • 好像你从来没有实例化过一个对象。您必须先执行此操作,然后才能对对象调用 show

标签: python-3.x string class


【解决方案1】:

现在来看看你的代码有多处问题。

首先在您的测试方法中进行以下更改 现在你的汽车类没有颜色方法。它只有一个您可以访问的颜色字段

def test(name,name2):
    print(name)
    print(name2)
    some_car = car(name, name2)
    some_car.show()
    print(some_car.color)
    time.sleep(30)

如果您想以某种方式将 arg 传递给 show 方法,请使用以下方法签名

def show(self, name)

如果类方法引用同一个对象,则为第一个参数。 Refer here for more info on Python3 classes

【讨论】:

  • 非常感谢。是的。似乎我无法理解将 arg 传递给显示方法的概念。再次感谢。
【解决方案2】:

缩进你的 show 方法,目前它在类 car 之外,因此问题很可能是因为你将 self 参数传递给函数而不是类方法。所以 self 被评估为一个字符串,当你使用 self.model 打印它时,它会抛出异常

【讨论】:

  • runfile('/home/stuff/script/QT/temp.py', wdir='/home/stuff/script/QT') audi blue Traceback(最近一次调用最后):文件“ /home/stuff/script/QT/temp.py”,第 49 行,在 info = threading.Thread (target=test(name,name2)) 文件“/home/stuff/script/QT/temp.py ",第 15 行,在测试 Car.show(name)
  • 以上是我的错误。我在选项卡问题中没有任何错误,因为 Spyder 会接听。
  • @otay 不,它不会因为语法是正确的,您也可以在 python 中添加类之外的函数。
【解决方案3】:

你在这些方面有问题:

car.show(name)
car.color(name2)

car 是 class(顺便说一句,约定是使用 Car)

car.show 只是一个函数,你传递一个字符串, 例如 'car.show('blue')' 导致 self.model 失败,因为 'blue'.model 有故障。

我很确定您打算在您的测试函数中实例化一辆汽车 与:

the_car = car(name, name2)
the_car.show()

【讨论】:

  • 谢谢!在课堂上纠正我是汽车而不是汽车。似乎在函数 print(name) 和 print(name2) 中确实收到了来自 txt 文件的字符串,但我无法传递给 Car.show(name)。我是新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
  • 2021-09-25
  • 2014-03-04
相关资源
最近更新 更多