为什么在创建类对象时在python中出现属性错误

Why do I get Attribute Error in python while creating a class objects

提问人:Kayboy 提问时间:11/17/2023 最后编辑:MatthiasKayboy 更新时间:11/17/2023 访问量:27

问:

如果我经常有 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())
Python 对象 初始化 属性Error

评论

1赞 Matthias 11/17/2023
这甚至不应该运行,因为语法无效。请确保您的问题包含正确的缩进代码。请提供完整和准确的错误消息。def_init_(self, name, email, age):
0赞 cards 11/17/2023
在正确的条件下(参见 Matthias 的评论),您可以通过调用 method 作为接受对象作为参数的函数来获得您想要的东西:greeting(kay)

答:

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