Home > Software design >  AttributeError when try "getter" in python
AttributeError when try "getter" in python

Time:08-17

When I learning getter and setter in python I try below codes. So I create getter to private attribute called _age in class Warrior . But getter in not getting value in _age and give AttributeError: 'Warrior' object has no attribute 'age'. Did you mean: '_age'.

Can someone tell why??? and How to fix it.

class Warrior:

    def __init__(self, name):
        #instance attributes
        self.name = name
        self._age = 0

        #using property decorator
        #getter function
    
        @property
        def age(self):
            return self._age

        @age.setter
        def age(self, age):
            if age > 0:
                self._age=age
            else:
                print("Age Should be greater than zero")

warrior = Warrior("worr1")
print(warrior.name)
print(warrior.age)

also try setteras

warrior.age = 5
print(warrior.age)

CodePudding user response:

Your indentation is wrong. Your property defs should be one level less indented

class Warrior:

    def __init__(self, name):
        #instance attributes
        self.name = name
        self._age = 0

        #using property decorator
        #getter function
    
    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, age):
        if age > 0:
            self._age=age
        else:
            print("Age Should be greater than zero")

warrior = Warrior("worr1")
print(warrior.name)
print(warrior.age)
  • Related