Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AttributeError when try "getter" in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

warrior.age = 5
print(warrior.age)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading