Python classes do not have the concept of restricting access to member variables. All variables are treated as public.
Therefore, it is possible to create a pseudo-private variable, but when I tried to use it together with class inheritance, I got stuck, so I made a note as a troubleshooting.
error_case
class BaseClass(object):
def __init__(self):
self.__param = "I'm BaseClass"
class ChildClass(BaseClass):
def hello(self):
print self.__param
ChildClass().hello()
AttributeError Traceback (most recent call last)
## Pseudo private variable
You can create a pseudo private variable by prefixing the name of a member variable with two underscores.
However, internally, prepare a public variable named ``` _ {classname} __ {variable name}` ``, and refer to it from within the class with the name `` `__ {variable name}` ``. I'm just trying to do it. That's why it's a "pseudo" private variable.
#### **`sample_program`**
```python
class Sample(object):
def __init__(self):
self.__param = "I'm Sample"
sample = Sample()
print sample.__param
AttributeError Traceback (most recent call last)
#### **`sample_program`**
```python
sample = Sample()
print sample._Sample__param
"I'm Sample"
## Combination with class inheritance
As in the error case at the top, ** an attempt to access a pseudo-private variable set by a method in the parent class from inside the child class fails **.
Apparently the cause is due to the internal specifications of the pseudo-private variable.
Pseudo-member variables declared in the parent class seem to be internally plunged into `` `self._BaseClass__param```, even if they are inherited.
On the other hand, when you try to see `` `self.__param``` from a child class, it is naturally `` `_ChildClass__param``` that is referenced, so an error saying that there is no such variable will be returned.
## solution
If you use class inheritance, declare getters together in the parent class.
#### **`successful_case1`**
```python
class BaseClass(object):
def __init__(self):
self.__param = "I'm BaseClass"
def get_param(self):
return self.__param
class ChildClass(BaseClass):
def hello(self):
print self.get_param()
"I'm BaseClass"
(Update) Make it a property of the parent class. It is possible to prevent direct setting from the outside.
#### **`successful_case2`**
```python
class BaseClass(object):
def __init__(self):
self.__param = "I'm BaseClass"
@property
def _param(self):
return self.__param
class ChildClass(BaseClass):
def hello(self):
print self._param
It may be a situation that rarely happens, but it is unexpectedly inconvenient.
version
2.7.12 |Anaconda 4.2.0 (x86_64)| (default, Jul 2 2016, 17:43:17) \n[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)]
Recommended Posts