はじめに
Pythonのプライベート変数の挙動についてメモします。
Pythonのプライベート変数
Pythonでは変数名の頭にアンダースコアを2個付けることでプライベート変数を定義できる。
employee.py
class Employee:
def __init__(self, salary):
self.__salary = salary
もちろんクラス内部からはアクセス可能。
employee.py
class Employee:
def __init__(self, salary):
self.__salary = salary
def get_salary1(self):
return self.__salary
@classmethod
def get_salary2(cls, instance):
return instance.__salary
内部的な仕組み
プライベート変数はクラス内部で以下の形式に変換され保持されている。
_{クラス名}{プライベート変数名}
上記のEmployeeクラスだとプライベート変数はクラス内部で次の名前で保持される。
_Employee__salary
また、内部的に変換されたプライベート変数にはアクセス可能。
sample
from employee import Employee
emp = Employee(5)
print(emp.__dict__)
>>>>{'_Employee__salary': 5}
print(emp._Employee__salary)
>>>> 5
クラス継承時の挙動
クラス継承時に、親クラスのプライベート変数は内部的に"__{親クラス名}{プライベート変数名}"と扱われるため
サブクラスから単純にはアクセスできない。
(サブクラスからプライベート変数にアクセスしようとすると、内部的には"__{サブクラス名}{プライベート変数名}"と解釈されるため)
employee.py
class Employee:
def __init__(self):
self.__salary = 100
def get_salary1(self):
return self.__salary
@classmethod
def get_salary2(cls, instance):
return instance.__salary
class TemporaryEmployee(Employee):
def get_salary(self):
return self.__salary
tmp = TemporaryEmployee()
tmp.get_salary()
>>>> AttributeError: 'TemporaryEmployee' object has no attribute '_TemporaryEmployee__salary'