成員修飾符:公有成員、私有成員 __字段名(無法直接訪問,只能間接訪問)
普通字段私有化
class Foo:
def __init__(self, name, age):
self.name = name
# self.age = age # 公有
self.__age = age # 私有,外部無法直接訪問
def show(self):
return self.__age
obj = Foo('alex', 19)
print(obj.name)
# print(obj.__age) # AttributeError: 'Foo' object has no attribute '__age'
print(obj.show()) # 19,可以間接地訪問到
靜態字段私有化
class Foo:
__v = '123'
def __init__(self):
pass
def show(self):
return Foo.__v
ret = Foo().show()
print(ret) # 123
class Foo:
__v = '123'
def __init__(self):
pass
def show(self):
return Foo.__v
@staticmethod
def stat():
return Foo.__v
ret = Foo.stat()
print(ret) # 123
方法的私有化
class Foo:
def __f1(self):
return 123
def f2(self):
r = self.__f1()
return r
obj = Foo()
ret = obj.f2()
print(ret) # 123 通過f2間接地拿到f1
繼承後的私有成員是否可以訪問
class F:
def __init__(self):
self.ge = 456
self.__gene = 123
class S(F):
def __init__(self, name):
self.name = name
self.__age = 18
super(S, self).__init__()
def show(self):
print(self.name) # alex
print(self.__age) # 18
print(self.ge) # 456
print(self.__gene) # AttributeError: 'S' object has no attribute '_S__gene'
s = S('alex')
s.show()
在子類中,只能訪問父類中的公有成員,不能訪問私有成員