python高级类与对象深度

1.   abc模块 ,不要以abc为模块名称

class Demo(object):
def __init__(self, li):
self.li = li
def __len__(self):
return len(self.li)
l = ['c', '李云', '九折']
d = Demo(l)
print(d) # <__main__.Demo object at 0x00000218C9347160>
print(len(d)) # 会触发__len__ 返回 3
如何判断Demo中是否含有 __len__魔法方法
print(hasattr(d,'__len__')) # 判断d的内部是否含有__len__ 返回为bool

2.第一种方法实现:子类重写父类的方法,

class CacheBase(object):
def dele(self):
raise NotImplementedError
def crea(self):
raise NotImplementedError
class RedisBase(CacheBase):
"""
1. 子类 如果不重写 父类的方法,访问时,就会报错
"""
def crea(self):
print('hahah')
r = RedisBase()
主动抛出异常:调用时才会检测
r.crea()
r.dele()
r.crea()
3.
第二种方法实现:子类重写父类的方法,
import abc
# 注意:不直接继承object 而是继承abc.ABCMeta
class CacheBase(metaclass=abc.ABCMeta):
@abc.abstractmethod
def dele(self):
pass
@abc.abstractmethod
def crea(self):
pass
class RedisBase(CacheBase):
def dele(self):
pass
def crea(self):
pass
# r = RedisBase()
# r.crea()
# r.dele()

# 抽象基类:实例化的时候检测
# 主动抛出异常:调用时才会检测
4.type 和isinstance()的区别
a = 1
b = '23'
print(isinstance(b,(int,str))) # 返回bool类型 ()元组类型----or运算
print(type(a)) # <class 'int'>

class Father(object):
pass
class Son(Father):
pass
ls = Son()
# print(isinstance(ls, Son))
# print(isinstance(ls, Father)) # True 继承
# print(type(ls) is Son) # 判断是否是一个内存地址
# print(type(ls) is Father) # False 不考虑继承关系
# print(f'Son_id:{id(Son)}, father_id:{id(Father)}')

# is 是否引用同一个对象 即id是否相等
# == 判断值是否相等

# 当对象有自己的实例属性的时候,就直接输出自己的属性
# 当对象没有该属性属性时候,才会去类对象中找
5.# 自省机制:查询对象的内部结构
class Person(object):
name = 'haha'
class Student(Person):
def __init__(self, school_name):
self.school_name = school_name
hty = Student('logic_edc')
# print(hty.__dict__) # {'school_name': 'logic_edc'} 当前对象的属性 {"属性":"属性值"}
# print(dir(hty)) # 考虑到继承的成员 返回类型是列表
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'school_name']
6. 重写父类的方法
class Person(object):
def __init__(self,name,age,weight):
self.name = name
self.age = age
self.weight = weight
def speak(self):
print(f"{self.name}说:我{self.age}岁")
class Student(Person):
def __init__(self,name,age,weight,grade):
# 调用父类的初始化方法
# super().__init__(name,age,weight)
Person.__init__(self,name, age, weight)
self.grade = grade
def speak(self):
print(f"{self.name}说:我{self.age}岁,我在{self.grade}年级")
# hz = Student('小明',20,120,2)
# hz.speak()
7.多继承
class A(object):
def __init__(self):
print('A')
class C(A):
def __init__(self):
print('C')
super().__init__()
class B(A):
def __init__(self):
print('B')
super().__init__()
class D(B,C):
def __init__(self):
print('D')
super().__init__()
if __name__ == '__main__':
d = D()
print(D.__mro__)




posted @ 2020-07-11 15:14  枫叶少年  阅读(217)  评论(0编辑  收藏  举报