class Person:
def __init__(self, name, age, profession):
# data members (instance variables)
self.name == name
self.age == age
self.prof == profession
#Behavior(instance methods)
def _show(self):
print('Name:', self.name, 'Age:', self.age, 'Profession:', self.profession)
# Behavior (instance methods)
def _work(self):
print(self.name, 'working as a', self.prof)
# create an object of a class
john = Person('John', 19, 'Robotics Engineer')
# call methods
john.show()
john.work()
AttributeError:“人”对象没有属性“名称”
您在标题中提到的错误正在发生,因为您部分地通过具有 2 个等号而不是分配它们来比较值( )__init__
self.name == name
self.name = name
并且还在类中定义函数 show & work以便访问它。
正确代码:
class Person:
def __init__(self, name, age, profession):
# data members (instance variables)
self.name = name
self.age = age
self.prof = profession
#Behavior(instance methods)
def show(self):
print('Name:', self.name, 'Age:', self.age, 'Profession:', self.prof)
# Behavior (instance methods)
def work(self):
print(self.name, 'working as a', self.prof)
# create an object of a class
john = Person('John', 19, 'Robotics Engineer')
# call methods
john.show()
john.work()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句