如何解决“元组对象没有属性”的问题?

3

我在做一道作业题,但是我一直得到一个错误提示:在__init__函数中的元组没有age属性,但事实上它确实存在。

我尝试使用x[y]这种方式来解决问题,但是没有成功。 以下是代码:

class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
time=2019
p1=(input("Name: "),input("Age: "))
clock=100-p1.age
time=time+clock
print("Hi "+ p1.name +"! You will turn 100 in "+ clock+"!")

我收到了以下信息:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    clock=100-p1.age
AttributeError: 'tuple' object has no attribute 'age'

你从哪里得到的想法,认为它曾经到达过__init__方法?在定义类之后,你再也没有提到过名称Person,因此__init__永远不会被调用。 - ShadowRanger
1个回答

4
p1=(input("Name: "),input("Age: "))

现在,你正在创建一个2元组,而不是一个Person对象。应该改成:

p1 = Person(input("Name: "), input("Age: "))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接