AttributeError when try "getter" in python

Question:

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)
Asked By: Haritha Thushanka

||

Answers:

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)
Answered By: Nick Bailey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.