Home > Software design >  AttributeError: 'Person' object has no attribute 'name' Error please help me
AttributeError: 'Person' object has no attribute 'name' Error please help me

Time:04-06

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: 'Person' object has no attribute 'name'

CodePudding user response:

The error you've mentioned in the title was occurring because you are comparing values in __init__ part by having 2 equal signs self.name == name rather than assigning them (self.name = name)

And also define function show & work inside the class in order to access it.

Correct code:

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