面向对象——反射及动态导入(三十二)
反射:主要指程序可以访问,检测和修改它本身状态或行为的一种能力(自省)
四个可以实现自省的函数
一下方法适用于类和对象
hasattr(object, name)
判断object中有没有一个name字符串对应的方法和属性
getattr(object, name, default=None)
setattr(x, y, v)
delattr(x, y)
class People: __star = "earth" def __init__(self,name,id,sex): self.Name = name self.Id = id self.Sex = sex def get_star(self): print("%s" %(self.__star)) p1 = People("zhangsan",123456,"male") p1.get_star() print(hasattr(p1,"Name")) # True print(hasattr(p1,"get_star")) # True print(getattr(p1,"Id")) # 123456 print(getattr(p1,"abcd", "没有这个参数")) # 没有这个参数 print(getattr(p1,"get_star")) # ''' <bound method People.get_star of <__main__.People object at 0x000001E3D1448940>> ''' fun = getattr(p1,"get_star") fun() print(p1.__dict__) # {'Name': 'zhangsan', 'Id': 123456, 'Sex': 'male'} setattr(p1,"Height",180) setattr(p1,"func",lambda x:x+1) print(p1.__dict__) # {'Height': 180, 'Name': 'zhangsan', 'func': <function <lambda> at 0x000002603DB67B70>, # 'Sex': 'male', 'Id': 123456} print(p1.func(2)) delattr(p1,"Sex") print(p1.__dict__) # {'Height': 180, 'Id': 123456, 'Name': 'zhangsan'} if hasattr(p1,"Sex"): print("%s" %p1.Sex) else: print("do something...")
动态导入
module_t = __import__("m1.test1") # 传入字符串 print(module_t) module_t.test1.test2() ''' <module 'm1' from 'E:\\06_python\\python_demo\\test3\\OO\\m1\\__init__.py'> test2... '''
# m1/test1 def test1(): print("test1...") def test2(): print("test2...")
注意
# m1/test1 def test1(): print("test1...") def _test2(): # _ 声明为私有 print("test2...")
from m1.test1 import * # 导入所有 test1._test2() # 报错
module_t = __import__("m1.test1") # 传入字符串 print(module_t) # <module 'm1' from 'E:\\06_python\\python_demo\\test3\\OO\\m1\\__init__.py'> module_t.test1.test1() # test1... import importlib m = importlib.import_module("m1.test1") print(m) # <module 'm1.test1' from 'E:\\06_python\\python_demo\\test3\\OO\\m1\\test1.py'> m.test1() # test1...