小学生绞尽脑汁也学不会的python(反射)
1. issubclass, type, isinstance
issubclass 判断xxxx类是否是xxxx类的子类
type 给出xxx的数据类型. 给出创建这个对象的类
isinstance 判断xxx对象是否是xxx类型的
class Animal:
pass
class Cat(Animal):
pass
class BoSiCat(Cat):
pass
print(issubclass(Cat, Animal)) # 判断第一个参数是否是第二个参数的后代
print(issubclass(Animal, Cat))
print(issubclass(BoSiCat, Animal)) # True
# class Animal:
# pass
#
# class Cat(Animal):
# pass
#
# class BoSiCat(Cat):
# pass
#
# c = Cat()
# print(type(c)) # 比较精准的给出对象的类
# 计算a+b的结果并返回. 两个数相加
# def add(a, b):
# if (type(a) == int or type(a) == float) and (type(b) == int or type(b) == float):
# return a + b
# else:
# print("算不了")
#
# print(add("胡汉三", 2.5))
class Animal:
pass
class Cat(Animal):
pass
class BoSiCat(Cat):
pass
# a = Animal()
# print(isinstance(a, Animal)) # 自己类可以判断
# print(isinstance(a, Cat)) # 子类不能判断
c = BoSiCat()
print(isinstance(c, Animal)) # True 子类的对象可以当成父类的类型来看.
# isinstance判断的是对象是否是xxx家族体系的内容. 往上找
lst = "马化腾"
print(type(lst.__iter__()))
2. 如何分辨方法和函数.
在外面定义的函数一定是函数
在类中:
1. 实例方法: 如果是对象访问.方法,, 如果是类名访问是函数
2. 静态方法: 都是函数
3. 类方法: 都是方法
如果想要用程序来判断. 需要引入两个模块
from types import FunctionType, MethodType
isinstance()
def func():
print("我是func")
print(func) #
class Foo:
# 实例方法: 对象.方法 方法 类名.方法 函数
def chi(self):
print("我是吃")
@staticmethod # 都是函数
def static_method():
pass
@classmethod # 都是方法
def class_method(cls): # 类对象的内容
pass
@property # 神马都不是. 变量
def age(self):
return 10
# 引入两个模块
from types import FunctionType, MethodType
def haha(arg):
print(isinstance(arg, FunctionType)) # False
print(isinstance(arg, MethodType)) # True
haha(Foo.age)
# f = Foo()
# print(f.chi) # >
# Foo.chi(f)
# print(Foo.chi) #
#
# print(f.static_method) #
# print(Foo.static_method) #
#
# print(f.class_method) # >
# print(Foo.class_method) # >
3. 反射(重点)
仅限于内存层面
重点:
hasattr(obj, str) 判断对象中是否包含了xxx(str)
getattr(obj, str) 从对象中获取xxxx(str)
次重点:
setattr(obj, str, value) 给对象设置xxxx(str)属性值(value)
delattr(obj, str) 从对象中删除xxxxx(str)信息
class Person:
def __init__(self, name):
self.name = name
self.age = None
def chi(self):
print("人喜欢吃东西%s" % self.name)
p = Person("刘伟")
setattr(p, "name", "大阳哥") # 动态的给对象设置属性和值
setattr(p, "age", 18) # 很少用. 慎用
print(p.age)
delattr(p, "age")
print(p.age)
# p.chi()
# val = input("请输入你想让刘伟执行的动作:")
# if hasattr(p, val):
# getattr(p, "name")
# func = getattr(p, val)
# func()