提问人:Kayboy 提问时间:11/17/2023 最后编辑:MatthiasKayboy 更新时间:11/17/2023 访问量:27
为什么在创建类对象时在python中出现属性错误
Why do I get Attribute Error in python while creating a class objects
问:
如果我经常有 AttributeError,我该怎么办。它一直说“User”对象没有属性。我需要再次做出任何声明吗?
这是我的代码:
class User:
def_init_(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f' My name is {self.name} and I am {self.age} years, you can contact me on my email{self.email}'
kay= User('Kayboy', '[email protected]', 18)
print(kay.greeting())
答:
1赞
Tricotou
11/17/2023
#1
您可能犯了缩进错误。 错误代码:
class User:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age} years, you can contact me on my email{self.email}'
kay= User('Kayboy', '[email protected]', 18)
print(kay.greeting())
这里的 greeting 是一个独立的函数,不是 User 类的一部分。并且您有属性错误调用kay.greeting
正确代码:
class User:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age} years, you can contact me on my email{self.email}'
kay= User('Kayboy', '[email protected]', 18)
print(kay.greeting())
评论
def_init_(self, name, email, age):
greeting(kay)