isinstance、issubclass、反射

一、isinstance、issubclass

# isinstance(obj, cls)
    检查obj是否是cls的对象
class A(object):pass a = A() print(isinstance(a, A)) # True # issubclass(sub, super) 检查sub是否是super的派生类
class A(object):pass class B(A):pass print(issubclass(B, A)) # True

二、反射

用字符串形式的名字去操作对象相关的属性(python中一切皆对象)

hasattr、getattr

class A(object):
    def __init__(self, name):
        self.name = name

    def func(self):
        print("func")

a = A("pd")

# 反射对象的属性
if hasattr(a, "name"):
    ret = getattr(a, "name")
    print(ret)

# 反射对象的方法
if hasattr(a, "func"):
    getattr(a, "func")()  # func
View Code
class A(object):
    name = "pd"

    @classmethod
    def func(self):
        print("func")

# 反射类的属性
if hasattr(A, "name"):
    ret = getattr(A, "name")  # pd
    print(ret)

# 反射类的方法
if hasattr(A, "func"):
    getattr(A, "func")()  # func
View Code
# demo.py
name = "pd"

def func():
    print("func in demo")

#########################

# test.py
import demo

# 反射模块的属性
if hasattr(demo, "name"):
    ret = getattr(demo, "name")
    print(ret)
    
#反 射模块的方法
if hasattr(demo, "func"):
    getattr(demo, "func")()
View Code
import sys

name = "pd"

def func():
    print("func")

#反射本模块中的属性
if hasattr(sys.modules["__main__"], "name"):
    ret = getattr(sys.modules["__main__"], "name")
    print(ret)  # pd

#反射本模块中的函数
if hasattr(sys.modules["__main__"], "func"):
    getattr(sys.modules["__main__"], "func")()  # func
View Code

setattr:设置/修改变量
delattr:
删除一个变量

class A(object):
    name = "盲僧"

    def __init__(self, name):
        self.name = name

a = A("pd")

setattr(a, "name", "诺手")
setattr(A, "name", "德玛")
print(a.name)  # 诺手
print(A.name)  # 德玛

delattr(a, "name")
print(a.name)  # 德玛  对象的name属性已被删除,就找类的

delattr(A, "name")
print(A.name)  # 报错  类中的name也被删除,找不到了

 

posted @ 2018-09-15 17:03  就俗人一个  阅读(169)  评论(0编辑  收藏  举报