Python之 ---成员修饰符

时间:2023-03-09 16:50:43
Python之 ---成员修饰符

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

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

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

 class Goo:
def __init__(self,name,age):
self.name=name
self.age=age
obj=Goo('wing',)
print(obj.age)

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

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

 class Goo:
def __init__(self,name,age):
self.name=name
self.__age=age
obj=Goo('wing',)
print(obj.__age) 执行结果:
Traceback (most recent call last):
File "D:/Study/面向对象/成员修饰符.py", line , in <module>
print(obj.__age)
AttributeError: 'Goo' object has no attribute '__age'

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

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

 class Goo:
def __init__(self,name,age):
self.name=name
self.__age=age
def show(self):
return self.__age
obj=Goo('wing',)
ret =obj.show()
print(ret)

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

 class fOO:
def __show(self):
return
obj=foo()
ret =obj.__show()
print(ret) 执行结果:
 Traceback (most recent call last):
File "D:/Study/面向对象/成员修饰符.py", line , in <module>
print(obj.__age)
AttributeError: 'Goo' object has no attribute '__age'

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

 class Foo:
def __show(self):
return def f2(self):
return self.__show() obj=Foo()
ret=obj.f2()
print(ret)

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

 class Foo:
def __init__(self):
self.__gene=
class F(Foo):
def __init__(self,name):
self.name=name
self.__age=
super(F,self).__init__()
def show(self):
print(self.__age)
print(self.__gene)
s=F('aaa')
s.show()

执行结果:

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

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