Python 面向对象 (五) 成员修饰符
1.0 面向对象成员:
1.0.1 共同成员
1.0.2 私有成员,__attr,就是私有成员,外部没法直接访问。
class Foo: def __init__(self,name,age): self.name = name self.age = age self.__age= age obj = Foo() obj.name obj.age obj.__age #在外部没法访问
要想访问私有字段,就可以用其他方法,间接访问。
class Foo: def __init__(self,name,age): self.name = name self.age = age self.__age= age def show(self): return self.__age obj = Foo('rollo',25) result = obj.show() print(result)
静态字段,私有化
class Roo: __country = 'China' def __init__(self): pass def show(self): return Roo.__country obj = Roo() print(obj.show())
方法静态化访问:
class Roo: __country = 'China' def __init__(self): pass def show(self): return Roo.__country @staticmethod def strat(): return Roo.__country result = Roo.strat() print(result)
2.0 方法的私有化:
class Roo: def __f1(self): return 123 def f2(self): result = self.__f1() return result obj = Roo() ret = obj.f2() print(ret)
class Father: def __init__(self): self.__gender = "male" self.gender = "666" class Son(Father): def __init__(self,name): self.name = name self.__age = 13 super(Son,self).__init__() def show(self): print(self.name) print(self.__age) print(self.gender) print(self.__gender) obj = Son('Rollo') obj.show()