|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class C:
- def __init__(self,a):
- self.a=a
- def __fun1(self):
- print("fun1")
- def fun2(self):
- self.__fun1()
-
- class E(C):
- def fun(self):
- print("e")
复制代码
那为什么子类E调用父类的fun2
可以去打印出fun1
python 并没有严格意义上的私有方法,私有方法只是会给方法名加上 "_类名",
而在方法内部调用双下划线开头的方法,解释器也会自动加上 "_类名",
而在方法外部调用则需要你自己加上去了
>>> class C:
... def __init__(self,a):
... self.a=a
... def __fun1(self):
... print("fun1")
... def fun2(self):
... self.__fun1()
...
>>>
>>> class E(C):
... def fun(self):
... print("e")
...
>>>
>>> dir(C)
['_C__fun1', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'fun2']
>>> e = E(7)
>>> dir(e)
['_C__fun1', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'fun', 'fun2']
>>> e._C__fun1()
fun1
>>>
|
-
|