Day019--Python--反射

1. issubclass, type, isinstance

issubclass 判断XXX类是否是XXX类的子类  
type 给出XXX的数据类型. 给出创建这个对象的类
isinstance 判断XXX对象是否是XX类型的实例
  
class Animal:
    pass

class Cat(Animal):
    pass

class BoSiCat(Cat):
    pass


print(issubclass(Cat, Animal)) # 判断第一个参数是否是第二个参数的后代
print(issubclass(Animal, Cat))
print(issubclass(BoSiCat, Animal)) # True
issubclass()
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))
type()
 
 
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__()))

li = []
print(type(li.__iter__()))
isinstance

2. 如何分辨方法和函数
在外面定义的函数一定是函数
在类中:
1. 实例方法: 如果是对象访问,是方法. 如果是类名访问,是函数.
2. 静态方法: 都是函数
3. 类方法: 都是方法
如果想用程序来判断, 需要引入两个模块.
from types import FunctionType, MethodType
print(isinstance(arg, FunctionType)) 判断对象是否是函数
print(isinstance(arg, MethodType)) 判断对象是否是方法
def func():
    print("我是func")

print(func) # <function func at 0x00000253260678C8>

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.class_method)
haha(Foo.age)  # age不是函数,也不是方法,是变量


# f = Foo()
# print(f.chi) # <bound method Foo.chi of <__main__.Foo object at 0x0000022D69C48390>>
# Foo.chi(f)
# print(Foo.chi) # <function Foo.chi at 0x000001A4BBEE79D8>
# 
# print(f.static_method) # <function Foo.static_method at 0x000002BBD2DB7A60>
# print(Foo.static_method) # <function Foo.static_method at 0x00000233E2247A60>
# 
# print(f.class_method) # <bound method Foo.class_method of <class '__main__.Foo'>>
# print(Foo.class_method) # <bound method Foo.class_method of <class '__main__.Foo'>>
区分function和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()
setattr(),hasattr(),getattr()

准备两个py文件master和test,master中有写好的函数,在test中引入master,用test去测试。

def chi():
    print("大牛一顿吃100碗饭")

def he():
    print("大牛一顿喝一桶")

def la():
    print("大牛很能拉")

def shui():
    print("大牛一次睡一年")

name = "大牛"
master
import master

while 1:
    print("""大牛写了很多的功能:
    chi
    he
    la
    shui
""")
    val = input("请输入你要测试的功能") # he

    if hasattr(master, val):
        attr = getattr(master, val) # 从xxx对象或者模块中找xxxxx(字符串) 功能, 变量
        if callable(attr): # 判断这个鬼东西是否可以被调用
            attr()
        else:
            print(attr)
    else:
        print("没有这个功能")

    #如果不使用getattr(),则无法调用
    # master.val()
    #
    # master."chi"()

    # 低配版,手动录入,繁琐
    # if val == 'chi':
    #     master.chi()
    # elif val == "he":
    #     master.he()
    # elif val == "la":
    #     master.la()
    # elif val == "shui":
    #     master.shui()
    # else:
    #     print("滚犊子")


# 把chi函数换成lambda
print(master.chi)
setattr(master, "chi", lambda x: x + 1)
print(master.chi)
print(master.chi(1))
#
# delattr(master, "la") # 删除xxx
# master.la()
test


原文地址:https://www.cnblogs.com/surasun/p/9718991.html