day37-1 面向对象高阶

面向对象高阶

isinstance

  • 判断是否为实例化对象,以后可以用来取代type
  • 和type的区别:
class Foo:
    pass

class Bar(Foo):
    pass

b = Bar()
print(isinstance(b, Bar))   # True  未来推荐使用
print(isinstance(b, Foo))   # True  会检测父类

print(type(b) == type(Bar)) # False     type(b)是Bar
print(type(b) == type(Foo)) # False

print(type(b) == Foo)       # False
print(type(b) == Bar)       # True
  • isinstance:判断对象是否是这个类实例化出来的,实例化具有传递性,会检测父类
  • type:获取实例化出这个对象的类,不会检测父类

issubclass

  • 判断某个类是否是另一个类的子类(参数必须为类)
print(issubclass(Bar, Foo)) # True

反射(自省)

  • 通过字符串获取某些东西

模块的使用

import time

choice = input('choice func:>>>').strip()
print(getattr(time, choice)())

# 其实就是这个用法
# getattr(module, method)()

放在类的使用

  1. hasattr
  2. getattr
  3. setattr
  4. delattr
class Foo():
    count = 0
    def eat(self):
        print('eat')
        
f = Foo()
if hasattr(f, 'eat'):       # 判断有没有
    getattr(f, 'eat')()     # 获取    # 'eat'
    
f.count = 1
print(f.__dict__)           # {'count': 1}
setattr(f, 'eat', 222)      
print(f.__dict__)           # {'count':1, 'eat': 222}

print(getattr('eat'))       # 222

setattr(f, 'count', 11)
print(f.__dict__)           # {'count':11, 'eat':222}

delattr(f, 'count')         # {'eat': 222}
print(f.__dict__)
  • 可以用来写通用评论借口

call

class Foo:
    def __init__(self, name):
        self.name = name
        
    def __call__(self, *args, **kwargs):
        print('我触发了')
        
f = Foo('leijun')
f()     # 对象加括号出发call
我触发了

转载于:https://www.cnblogs.com/lucky75/p/11066827.html

猜你喜欢

转载自blog.csdn.net/weixin_34319111/article/details/94574775