Trouble with Python pseudo-private variables and class inheritance

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) in () ----> 1 ChildClass().hello() in hello(self) 5 class ChildClass(BaseClass): 6 def hello(self): ----> 7 print self.__param AttributeError: 'ChildClass' object has no attribute '_ChildClass__param'


## 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) in () 4 5 sample = Sample() ----> 6 print sample.__param AttributeError: 'Sample' object has no attribute '__param'



#### **`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

Trouble with Python pseudo-private variables and class inheritance
Python: Class and instance variables
Python class variables and instance variables
[Python] Inherit a class with class variables
[Python] How to play with class variables with decorator and metaclass
[Python] Class inheritance (super)
[python] Difference between variables and self. Variables in class
[Python] Class inheritance, override
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
About Python variables and objects
Python variables and object IDs
python with pyenv and venv
Class inheritance and super functions
Works with Python and R
I'm having trouble with instance variables being inherited in Python
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Install Python 2.7.9 and Python 3.4.x with pip.
perl objects and python class part 2.
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
[Python of Hikari-] Chapter 09-03 Class (inheritance)
Landmines hidden in Python class variables
Scraping with Python and Beautiful Soup
Python class definitions and instance handling
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Reading and writing NetCDF with Python
I played with PyQt5 and Python3
perl objects and python class part 1.
Reading and writing CSV with Python
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
I was addicted to confusing class variables and instance variables in Python
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
Create a Python function decorator with Class
Monitor Mojo outages with Python and Skype
[Python] Use and and or when creating variables
Build a blockchain with Python ① Create a class
FM modulation and demodulation with Python Part 3
[Automation] Manipulate mouse and keyboard with Python
Example of using class variables and class methods
Passwordless authentication with RDS and IAM (Python)
Python installation and package management with pip
Using Python and MeCab with Azure Databricks
Class variables
POST variously with Python and receive with Flask
Capturing images with Pupil, python and OpenCV
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
[Python] Variables