# # # # python 面向对象的三大特征之一 # # # # python多态:python中处处都是多态 python是一种弱类型的语言 # # # # java 是强类型语言 # # # # 比如:python中 name = "qq", java中 int_i = 666 如果之间直接改变类型。python可以直接改变,java则会报错 # # # # # # # python的鸭子类型:看着像鸭子,他就是鸭子。 # # # # 这些类中都有index 方法,这些类都互称为鸭子,这个不强制。不过尽量使用相同的方法名。可以抽象类统一化使用 # # # class Str: # # # def index(self): # # # pass # # # # # # class List: # # # def index(self): # # # pass # # # # # # class Tuple: # # # def index(self): # # # pass # # # # # # # 广义的封装:实例化一个对象,给对象封装一些属性 # # # 狭义的封装: 私有制 # # # 私有成员: 私有静态字段:私有方法,私有对象属性 # # # # class A: # # name = "yan" # # __age = "9999" # # def func(self): # # print(self.__age) # # print(A.__age) # # print("in the func") # # # # a = A() # # print(a.name) # # print(A.name) # # # print(A.__age) # 类名不能调用私有静态字段 # # # print()a.__age # 实例对象不能访问静态字段 # # # # 对于私有静态字段来说,类的外部不能访问 # # a.func() # 对于私有静态字段来说,类的内部可以访问 # # print(A.__dict__) # {‘__module__‘: ‘__main__‘, ‘name‘: ‘yan‘, ‘_A__age‘: ‘9999‘, ‘func‘: <function A.func at 0x000001D9035667B8>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘A‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘A‘ objects>, ‘__doc__‘: None} # # # 发现有_A__age 这个变量,想办法访问他 # # # # print(A._A__age) # # print(a._A__age) # 访问成功。最好不要使用这种方法 # # # # # class B: # # __money = 9999999999999 # # # # # # class A(B): # # name = "yan" # # __age = "9999" # # def func(self): # # print(self.__age) # # print(A.__age) # # print("in the func") # # # # def find_money(self): # # print(self._B__money) # 对于私有静态字段来说,只能在本类中内部访问,在类的外部或者其派生类中不可访问 # # # # a = A() # # a.find_money() # ok # # # print(A.__dict__) # # # # 私有方法 # # class B: # def __func(self): # print("$2000000000") # # def func2(self): # self.__func() # class A(B): # def __func(self): # print("func A") # # def func1(self): # super().func2() # 自动传self # self.__func() # 常规使用方法 # # a = A() # a.func1() # 常规方法 # # a._A__func() # 最好不要使用 # 面试题 class Parent: def __func(self): print("In the parent") def __init__(self): self.__func() class Son(Parent): def __func(self): print("In the son") s1 = Son()
class A: def __init__(self,name,age,sex): self.name = name self.__age = age self.__sex = sex def func(self): print(self.__age) a = A("y",999,"1") print(a.name) a.func() # print(a.__age) # 不能访问 # print(a.__dict__) # {‘name‘: ‘y‘, ‘_A__age‘: 999, ‘_A__sex‘: ‘1‘} print(a._A__age) # print(A._A__age) # AttributeError: type object ‘A‘ has no attribute ‘_A__age‘ # print(A.__dict__) # print(A.name) #AttributeError: type object ‘A‘ has no attribute ‘name‘
原文:https://www.cnblogs.com/yfjly/p/10591540.html