一.isinstance和issubclass

1.isinstance

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
class Animal:
    def eat(self):
        print('刚睡醒吃点儿东西')


class Cat(Animal):
    def play(self):
        print('猫喜欢玩儿')

c = Cat()

print(isinstance(c, Cat))  # c是一只猫
print(isinstance(c, Animal))  # 向上判断 c是一只动物

2.issubclass

 1 class Animal:
 2     def eat(self):
 3         print('刚睡醒吃点儿东西')
 4 
 5 
 6 class Cat(Animal):
 7     def play(self):
 8         print('猫喜欢玩儿')
 9 
10 c = Cat()
11 print(issubclass(Cat, Animal))  # 判断Cat类是否是Animal类的子类
12 print(issubclass(Animal, Cat))  # 判断Animal类是否是Cat类的子类

二.区分方法和函数

官方玩法

 1 from types import FunctionType,MethodType  # 方法和函数  FunctionType 函数类型 MethodType 方法类型
 2 from collections import Iterable, Iterator  # 迭代器
 3 
 4 
 5 class Person:
 6     def chi(self):  # 实例方法
 7         print('我要吃鱼')
 8 
 9     @classmethod
10     def he(cls):
11         print('我是类方法')
12 
13     @staticmethod
14     def pi():
15         print('你是真的皮')
16 
17 p =Person()
18 
19 print(isinstance(Person.chi, FunctionType)) # True
20 print(isinstance(p.chi, MethodType)) # True
21 
22 print(isinstance(p.he, MethodType)) # True
23 print(isinstance(Person.he, MethodType)) # True
24 
25 print(isinstance(p.pi, FunctionType)) # True
26 print(isinstance(Person.pi, FunctionType)) # True

野路子

打印的结果中包含了function. 函数
method. 方法
 1 def func():
 2     print('我是函数')
 3 
 4 class Foo:
 5     def chi(self):
 6         print('我是吃')
 7 
 8 print(func)  #<function func at 0x0000024817BF1E18>
 9 f = Foo()
10 f.chi()
11 print(f.chi)  # <bound method Foo.chi of <__main__.Foo object at 0x0000024817DCC358>>

 

三.反射

 1 class Preson:
 2     def __init__(self, name, laopo):
 3         self.name = name
 4         self.laopo = laopo
 5 
 6 
 7 p = Preson('宝宝', '林志玲')
 8 
 9 print(hasattr(p, 'laopo'))  # p这个对象中是否有老婆这个属性
10 print(getattr(p, 'laopo'))  # p.laopo 获取p这个对象中的老婆属性
11 
12 # 设置一个对象属性若存在就修改 不存在就添加到这个对象中
13 setattr(p, 'laopo', '胡一菲')  # p.laopo = 胡一菲
14 setattr(p, 'money', 10000000)  # p.money = 10000000
15 
16 print(p.laopo)
17 print(p.money)
18 
19 # delattr(p, 'laopo')  # 把对象中的xxx属性移除   != p.laopo = None
20 print(p.laopo)  #'Preson' object has no attribute 'laopo' 已经移除了对象中的laopo属性所以报错

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄