💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 1. @classmethod 类方法,不需要实例化对象就可以调用类方法(@classmethod修饰)和成员 ~~~ __author__ = 'dailin' class test: name="张馨予" def __init__(self,num): self.num=num print("test类初始化....") @classmethod def getTest(cls,num): print("名字是:%s"%cls.name) # 使用成员 return cls(num) # 创建对象并返回 def echoes(self): print("该Test对象的num是:%s"%(self.num)) test =test.getTest(10230) test.echoes() ~~~ 运行代码输出 ~~~ 名字是:张馨予 test类初始化.... 该Test对象的num是:10230 ~~~ ## 2. hasattr和getattr getattr调用方法或者导入类对象时使用 判断对象是否具有和调用对象某个方法 引用上边的类 ~~~ tester1 = test(41561) if(hasattr(tester1,"echos")): tester1.getattr(tester1,"echoes") ~~~ ## 3. 动态导入模块 1. 模块 ~~~ __author__ = 'dailin' class People: def say(self): print("hello python!") @classmethod def getPeople(cls): return cls() ~~~ 2. 导入对象的工具方法,导入类并调用类方法得到对象,然后调用对象方法 ~~~ from importlib import import_module def load_object(path): """Load an object given its absolute object path, and return it. object can be a class, function, variable or an instance. path ie: 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware' """ try: dot = path.rindex('.') except ValueError: raise ValueError("Error loading object '%s': not a full path" % path) module, name = path[:dot], path[dot+1:] mod = import_module(module) # 导入模块 try: obj = getattr(mod, name) # 导入类对象 except AttributeError: raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name)) return obj import sys print(sys.path) o = load_object("Stark.sayhello.People") people = o.getPeople() # 通过类方法获得对象实例 people.say() # 调用方法 ~~~ ~~~ ['E:\\Django\\Stark\\Arya', 'E:\\Django\\Stark', 'D:\\Python\\Python36\\python36.zip', 'D:\\Python\\Python36\\DLLs', 'D:\\Python\\Python36\\lib', 'D:\\Python\\Python36', 'D:\\Python\\Python36\\lib\\site-packages', 'D:\\Python\\Python36\\lib\\site-packages\\psutil-5.2.2-py3.6-win-amd64.egg', 'D:\\Python\\Python36\\lib\\site-packages\\helloworld-0.1-py3.6.egg', 'D:\\Python\\Python36\\lib\\site-packages\\sayhello-0.1-py3.6.egg', 'D:\\Python\\Python36\\lib\\site-packages\\win32', 'D:\\Python\\Python36\\lib\\site-packages\\win32\\lib', 'D:\\Python\\Python36\\lib\\site-packages\\Pythonwin'] hello python! ~~~