Demonstrates get and set methods and properties : property « Class « Python Tutorial






class MyClass(object):
    def __init__(self, name):

        self.__name = name

    def get_name(self):
        return self.__name

    def set_name(self, new_name):
        if new_name == "":
            print "A MyClass's name can't be the empty string."
        else:
            self.__name = new_name
            print "Name change successful."

    name = property(get_name, set_name)

    def talk(self):
        print "\nHi, I'm", self.name

crit = MyClass("Poochie")
crit.talk()

print crit.name
crit.name = ""
crit.name = "A"

crit.talk()








11.3.property
11.3.1.The property Function
11.3.2.Objects in the class namespace can be accessed directly using the module name and dot . syntax.
11.3.3.An example of using a class data attribute (foo):
11.3.4.Demonstrates get and set methods and properties
11.3.5.Python properties (or attributes) are dynamic.
11.3.6.Define and access Properties