0

I have this question regarding the advantage and disadvantage of @property in a Python Object. This morning i have read several posts and forum but i still have not a clear idea. I create to simple object in Python to understand the differences of a Object without and with @property. My questions are: when i need to use @property to create an object? is useful for simple object like the example? when i don't need to use @property for an Object?

class MyArithmetic(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def sum(self):
        return self.a + self.b

    def subtraction(self):
        return self.a - self.b

    def multiplication(self):
        return self.a * self.b

    def division(self):
        return self.a/self.b

test = MyArithmetic(10,5)
print test.sum()
print test.subtraction()
print test.multiplication()
print test.division()


class MyArithmetic2(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def sum(self):
        return self.a + self.b

    @property
    def subtraction(self):
        return self.a - self.b

    @property
    def multiplication(self):
        return self.a * self.b

    @property
    def division(self):
        return self.a/self.b

test2 = MyArithmetic2(10,5)
print test2.sum
print test2.subtraction
print test2.multiplication
print test2.division
Gianni Spear
  • 7,033
  • 22
  • 82
  • 131
  • To summarize the winning answer to that question: start with simple attributes, and convert to properties only when needed. Python is not Java. – Bas Swinckels Mar 21 '15 at 20:41
  • Thanks @BasSwinckels. Could i ask your definition of "when needed" in order to understand? Thanks in advance – Gianni Spear Mar 21 '15 at 20:42
  • 3
    properties enable a python class to retain the same interface, as the class evolves, i.e. you can start a class with just attributes, and after 1 year, realize that that one of the attribute needs more validation, then, you can re-implement it as a property, with input validation. the attribute (property) is still accessed as `MyClass.my_old_attribute` – Haleemur Ali Mar 21 '15 at 20:45
  • 1
    You simply do `self.sum = a + b` and be done with it. Only in case the sum is expensive to compute and hardly used you convert to property. Other case might be if you have computed properties, e.g. the temperature of your object is stored in an attribute `T_in_Celcius`. If you also want to provide a `T_in_Fahrenheit`, it is better to make that a property and calculate it on the fly using a property, so that the state is only saved in a single place. – Bas Swinckels Mar 21 '15 at 20:48

0 Answers0