Start New Discussion within our Software Development Community

In the following program how does the line r.size = 150, 100 actually set the values using this line -> size = property(getSize, setSize)? property has two arguments, getSize & setSize, it seems to me that would only allow it so get one value and set one value.

#!/usr/bin/python3

class Rectangle:
    def __init__(self):
        self.width = 0
        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)

r.size = 150, 100
print(r.width)

Also, what are some small projects I can do the improve me python OOP?

The assignment statement

r.size = 150, 100

is equivalent to

r.size = (150, 100)

As far as python's syntax is concerned, a single value is assigned, which is a tuple with 2 elements.

Also note the use of decorators to declare properties:

class Rectangle:
    def __init__(self):
        self.width = 0
        self.height = 0

    @property
    def size(self):
        return self.width, self.height

    @size.setter
    def setSize(self, size):
        self.width, self.height = size

r = Rectangle()
r.width = 10
r.height = 5
print(r.size)
r.size = 150, 100
print(r.width)

Did you check the projects for the beginner thread ?

Edit Notice that the same code runs correctly in python 2 only if Rectangle is declared with class Rectangle(object):. Otherwise it is an old style class in the sense of python 2 terminology, that is to say a survivor on Python 1's heroic era, and the property won't work as expected. Worse, there will be no warning !

This article has been dead for over six months. Start a new discussion instead.