-2

I'm a newbie python programmer.

I have some minor question about property that which is better.

In class, which is standard for accessing variable by property or by variable itself?

Example, between following codes which is better method, baz1 and baz2? Are there any differences between baz1 and baz2?

class Foo:
    def __init__(self):
        self._bar = 3

    @property
    def bar(self):
        return self._bar

    def baz1(self):
        return self.bar+1

    def baz2(self):
        return self._bar+1
  • Why are you even using `property`? Wouldn't a simple attribute `self.bar = 3` be enough? – Taku Apr 17 '18 at 00:47
  • What is your goal with the `@property` method? As far as I see, it is unneeded. –  Apr 17 '18 at 00:47
  • I code it because it is the pythonic way of getter. By [here](https://stackoverflow.com/questions/14594120/python-read-only-property), this is the way to make it variable private and readonly – Taeho Gwon Apr 17 '18 at 00:54
  • 1
    You should not care about privacy in Python. Attribute accesses can be made directly on the variable. Then, if you need to add some kind of computation/validation, you could add a property to modifiy the internal behavior without modifying the external API of your class. – TwistedSim Apr 17 '18 at 01:01

1 Answers1

1

If your goal is to block the modification of a variable, you can use a property on an attribute without a setter. This will raise a exception if someone try to modify the value. Note that this do not ensure that the variable cannot be modified:

class Foo:
    def __init__(self):
        self._bar = 3

    @property
    def bar(self):
        return self._bar

foo = Foo()
foo._bar  # output 3
foo.bar  # output 3
foo.bar = 1 # raise an exception
foo._bar = 1  # _foo will be change to 1

If you just want to access and modify the attribute outside of the instance. You don't have to use any king of property:

class Foo:
    def __init__(self):
        self.bar = 3

foo = Foo()
foo.bar  # output 3
foo.bar = 1  # _foo will be change to 1

if you want to do some computation or validation of the input, you can use a get/set property:

class Foo:
    def __init__(self):
        self._bar = 3

    @property
    def bar(self):
        return self._bar + 1

    @bar.setter
    def bar(self, new_bar):
        assert isinstance(new_bar, int)
        self._bar = new_bar

foo = Foo()
foo.bar  # output 4
foo.bar = 1  # _foo will be change to 1
foo.bar = 'bar'  # raise assertion error
TwistedSim
  • 1,960
  • 9
  • 23