How to use property function to create properties

Use property Function to create property

By using the property function we can create size property by combining the size getter and setter.


class Rectangle(object): 
    def __init__(self): 
        self.width = 0 # from w  w  w.j  a  va 2 s  .c  om
        self.height = 0 
    def setSize(self, size): 
        self.width, self.height = size 
    def getSize(self): 
        return self.width, self.height 
    size = property(getSize, setSize) 
r = Rectangle() 
r.width = 10 
r.height = 5 
print r.size 
print r.size = 150, 100 
print r.width 

In this new version of Rectangle, a property is created with the property function with the accessor functions as arguments, and this property is stored under the name size.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules