1. isinstance, type, issubclass
isinstance: 判断你给对象是否是 xx 类型的. (向上判断
type: 返回 xxx 对象的数据类型
issubclass: 判断 xxx 类是否 xxx 的子类
- class Animal:
- def eat(self):
- print("刚睡醒吃点儿东西")
- class Cat(Animal):
- def play(self):
- print("猫喜欢玩儿")
- c = Cat()
- print(isinstance(c, Cat)) # True
- print(isinstance(c, Animal)) # True
- a = Animal()
- print(isinstance(a, Cat)) # 不能向下判断 False
- print(type(a)) # 返回 a 的数据类型
- print(type(c)) # 精准的告诉你这个对象的数据类型
- # 判断. xx 类是否是 xxxx 类的子类
- print(issubclass(Cat, Animal)) # True
- print(issubclass(Animal, Cat)) # False
2. 如何区分方法和函数
在类中:
实例方法
如果是类名. 方法 函数
如果是对象. 方法 方法
类方法: 都是方法
静态方法: 都是函数
- from types import MethodType, FunctionType
- isinstance()
- from types import FunctionType, MethodType # 引入方法和函数的模块
- class Person:
- def chi(self): # 实例方法
- print("我要吃鱼")
- @classmethod
- def he(cls):
- print("我是类方法")
- @staticmethod
- def pi():
- print("你是真滴皮")
- p = Person()
- print(isinstance(Person.chi, FunctionType)) # True
- print(isinstance(p.chi, MethodType)) # True
- print(isinstance(p.he, MethodType)) # True
- print(isinstance(Person.he, MethodType)) # True
- print(isinstance(p.pi, FunctionType)) # True
- print(isinstance(Person.pi, FunctionType)) # True
3. 反射
一共就 4 个函数
- attr: attribute
- getattr()
从 xxx 对象中获取到 xxx 属性值
hasattr()
判断 xxx 对象中是否有 xxx 属性值
delattr()
从 xxx 对象中删除 xxx 属性
setattr()
设置 xxx 对象中的 xxx 属性为 xxxx 值
- class Person:
- def __init__(self, name,wife):
- self.name = name
- self.wife = wife
- p = Person("宝宝", "林志玲")
- print(hasattr(p, "wife"))
- print(getattr(p, "wife")) # p.wife
- setattr(p, "wife", "胡一菲") # p.wife = 胡一菲
- setattr(p, "money", 100000) # p.money = 100000
- print(p.wife)
- print(p.money)
- delattr(p, "wife") # 把对象中的 xxx 属性移除. 并不是 p.wife = None
- print(p.wife)
来源: http://www.bubuko.com/infodetail-2891504.html