目录
1.经典类和新式类区别
1.1类型区别:
经典类 通过type查看到的实例类型都叫instance
新式类 通过type查看到的实例类型是对象所对应的类名
#Python3中类的定义全是新式类,Python2中继承了object才是新式类,其余全是经典类
1.2继承顺序不同
经典类:深度优先 F-》D-》B-》A-》E-》C
新式类:C3算法 F-》D-》B-》E-》C-》A
#C3算法子类优先于父类检查
class A():
pass
def test(self):
print("from A")
class B(A):
pass
def test(self):
print("from B")
class C(A):
pass
def test(self):
print("from C")
class D(B):
pass
def test(self):
print("from D")
class E(C):
pass
def test(self):
print("from E")
class F(D,E):
pass
def test(self):
print("from F")
f = F()
f.test()
# 经典类: F -> D -> B -> A -> E -> C # 新式类: F -> D -> B -> E -> C -> A
2.方法
属性 静态属性 --》类属性 普通属性 --》实例属性 方法 普通方法(实例) 静态方法 类方法
class Atm():
name = "ATM"
def __init__(self): # 普通方法
self.country = "china"
def normal_mathod(self, name):
print("normal:")
print(self.name,name)
# 类方法
@classmethod
def class_method(cls, name):
print("classmathod:")
print(type(cls), cls)
print(cls.name, name)
# 静态方法
@staticmethod
def static_method(name):
print("static_method:")
print(Atm.name, name)
a1 = Atm()
#####实例调用类方法 、实例方法、 静态方法
# a1.normal_mathod("normalmethod")
# a1.class_method("classmethod") # 可以访问类属性,但不能访问实例属性
# a1.static_method("static") #可以访问类属性,不能访问实例属性
# __new__方法是静态方法
# __init__是实例方法
#可以通过类名调用类方法和静态方法
#通过类名调用实例方法,需要传入一个实例对象
Atm.normal_mathod(a1, "nomal_method") #需要传一个实例进去
Atm.class_method("classmethod")
Atm.static_method("static_method")
3.Python中的下划线
class Parent:
"""
this is parent
class
"""
tmp = "tmp"
_min = 1 # 保护属性
__max = 10 # 私有属性
def __init__(self):
self.name = "sc"
self._age = 5
self.__desc = "it"
def __make(self):
print("这是一个私有方法")
print(self.__desc)
def _protectmake(self):
print("这是一个保护方法")
def show(self):
print("这是一个普通实例方法")
print(self.__desc, self.__max)
class Child(Parent):
pass
def show(self):
print(self.__max) #自动转换为_Child__max
#子类对象也不能访问私有变量
"""
Parent
类属性 tmp _min __max
实例属性 name _age __desc --》_Parent__desc
实例方法 __make _protectmake show
"""
p = Parent()
c1 = Child()
# print(p.tmp, c1.tmp)
# print(p._min, p._age)
# print(c1._min, c1._age)
# p._protectmake()
# c1._protectmake()
# 访问私有变量 __max __desc __make
# print(p.__max, p.__desc) #不能访问
# p.show()
# 私有对象不能通过实例访问,只可以被类访问,子类对象也不能访问
# c1.show()
# __desc__查看命名空间内有哪些属性
# print(p.__dict__)
# print(p._Parent__desc) #伪私有,可以通过访问
# print(p._Parent__max)
# python 私有变量是一个伪私有
# __max --》类名__max
# 可以通过_类名__属性名 这种方式访问到私有成员
# 查看对象的属性方法
# dir 查看对象的属性和方法,但是无法区分属性和方法
# print(dir(p))
# __dict__了解哪些是属性,哪些是方法
# print(p.__dict__)
# print(Parent.__dict__)
# help(Parent)
# 在类函数或模块里面的一个三引号引起来的字符串就是文档注释
# print(Parent.__doc__)
# 类名
# print(Parent.__name__)
# #类所在模块
# print(Parent.__module__) #--》相当于内建变量__name__
#
# #查看父类
# print(p.__class__)
#
# #查看父类
# print(Child.__bases__)
# #哈希查看属于哪一类
# print(c1.__hash__)