quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

Property overridden for "Explicit return in __init__" anti-pattern #64

Closed noisygecko closed 9 years ago

noisygecko commented 9 years ago

On this page: http://docs.quantifiedcode.com/python-code-patterns/correctness/explicit_return_in_init.html

Setting self.area in __init__() overrides the 'area' property created with the decorator. It should be changed to something like this (renamed area variable to _area):

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._area = width * height

    @property
    def area(self): # moved the logic for returning area to a separate method
        print 'in area()'
        return self._area
noisygecko commented 9 years ago

Also, the class definition should inherit from object. The code works since only the @property decorator is used (even though the documentation says that properties are only available for "new-style classes"). But if you try to add the @area.setter decorator, it will not work -- it will silently not create a setter method.

vogelsgesang commented 9 years ago

Thanks for reporting this bug and sorry that it take so much time until it was fixed. I just fixed it in the source code. It still might take some time until the fixes are online, but it should be online within the next week.