user10163680
user10163680

Reputation: 263

Does @property is a way to access the private and protected members inside the class?

I am trying to learn a object oriented programming. I read different codes regarding @property. According to my understanding @property is a way to access the private members within a class. What if I replace all the protected and private members as public and skip @property decorator.

class DataSet(object):
    def __init__(self, MC_Samples, labels):
    assert MC_Samples.shape[0] == labels.shape[0], (
    self._num_samples = MC_Samples.shape[0]

    self._MC_Samples = MC_Samples
    self._labels = labels
    self._epochs_completed = 0
    self._index_in_epoch = 0

    @property
    def MC_Samples(self):
        return self._MC_Samples
    @property
    def labels(self):
        return self._labels

    @property
    def epochs_completed(self):
        return self._epochs_completed

Upvotes: 3

Views: 528

Answers (2)

blue note
blue note

Reputation: 29071

There are not private and protected properties in python. By convention, variables starting with _ should be treated as private, but the language does not force it.

Now, regarding properties: In static languages eg. java, you ofter see this pattern

class Test {
    int x;
    int getX() { return x;}
    void setX(int value) { this.x = value;}
}

These getters and setters do absolutely nothing to promote encapsulation. You could just as well write test.x =5 instead of test.setX(5). However, you have to use them, just in case something changes later.

In python, you use the opposite approach. Prefer to have a public x, and write test.x =5. Properties are getters and setters that are added later, only if you need them.

So, if your class was initially

class Test:
    def __init__(self, x):
       self.x = x

feel free to write

test = Test(5)
test.x = 10

If later, eg, you want your x to be float, you remove the x variable, and add a x property

class Test:
    @property
    def x(self):
        return float(self._x)

    @property.setter
    def x(self, value):
        self._x = float(value)

You have now removed the test.x variable, and created two new methods. From now on, when you use test.x, or you assign to it, these two methods are called instead. These read/write to an interval _x variable, which is the old test.x (this is just the most common case though, they could do absolutely anything)

Upvotes: 2

Spasel Togalk
Spasel Togalk

Reputation: 99

@property mostly have 2 uses -

  1. As an access for protected variables within a class (Encapsulation)
  2. As an access for dynamic attribute, when validation / logic is involved. Usually comes in pairs with setters.

Upvotes: 1

Related Questions