爱陪小樱桃

导航

 

一:成员修饰符:分为共有成员和私有成员:

私有成员:__通过两个下滑线;无法直接访问,要访问只能间接访问;

如下我们定义了一个对象,里面有两个共有的成员变量,成员变量是共有的时候我们可以外部访问,如果私有的我们不能访问:

1 class Goo:
2     def __init__(self,name,age):
3         self.name=name
4         self.age=age
5 obj=Goo('wing',12)
6 print(obj.age)

如上可以访问,obj.age可以访问;

1.2如下显示的是私有的成员变量:无法外部访问

 1 class Goo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.__age=age
 5 obj=Goo('wing',12)
 6 print(obj.__age)

10 执行结果: 11 Traceback (most recent call last): 12 File "D:/Study/面向对象/成员修饰符.py", line 13, in <module> 13 print(obj.__age) 14 AttributeError: 'Goo' object has no attribute '__age'

如上提示是私有的无法访问

1.3如上的不能直接访问,我们可以通过如下的方法间接访问:

1 class Goo:
2     def __init__(self,name,age):
3         self.name=name
4         self.__age=age
5     def show(self):
6         return self.__age
7 obj=Goo('wing',12)
8 ret =obj.show()
9 print(ret)

1.4只要带有下滑——的都不可以访问了:

1 class fOO:
2     def __show(self):
3         return 123
4 obj=foo()
5 ret =obj.__show()
6 print(ret)

执行结果:
1 Traceback (most recent call last):
2   File "D:/Study/面向对象/成员修饰符.py", line 13, in <module>
3     print(obj.__age)
4 AttributeError: 'Goo' object has no attribute '__age'

 

1.5私有方法也可以通过间接访问,我们可以定义一个共有的方法,然后通过共有的方法,简接的访问私有的私有的方法,然后通过对象调用共有的方法,然后通过间接访问来访问私有的方法;

 1 class Foo:
 2     def __show(self):
 3         return 123
 4 
 5     def f2(self):
 6         return self.__show()
 7 
 8 obj=Foo()
 9 ret=obj.f2()
10 print(ret)

1.6那我们现在来思考一个问题:如果父类里面有私有成员,我们在子类里面能够访问吗?

 1 class Foo:
 2     def __init__(self):
 3         self.__gene=123
 4 class F(Foo):
 5     def __init__(self,name):
 6         self.name=name
 7         self.__age=12
 8         super(F,self).__init__()
 9     def show(self):
10         print(self.__age)
11         print(self.__gene)
12 s=F('aaa')
13 s.show()

执行结果:

1 F:\python3\python.exe D:/Study/面向对象/成员修饰符.py
2 Traceback (most recent call last):
3   File "D:/Study/面向对象/成员修饰符.py", line 31, in <module>
4     s.show()
5   File "D:/Study/面向对象/成员修饰符.py", line 29, in show
6     print(self.__gene)
7 AttributeError: 'F' object has no attribute '_F__gene'

通过上述案例说明:子类的不可以访问父类的私有的成员,如果想要访问,我们需要在父类里面间接的访问私有的成员,然后子类继承了父类,子类的对象,直接可以调用父类的那个间接的方法,就可以间接的访问父类的私有的成员变量了;

 

posted on 2017-11-01 17:17  cherry小樱桃  阅读(284)  评论(0编辑  收藏  举报