开发者

Calling a method of a class, the classname is a variable

开发者 https://www.devze.com 2023-02-22 21:17 出处:网络
I came up with this solution. But this looks too complicated. There must be a better and easier way.And second : is there a way to dynamically import the class ?

I came up with this solution. But this looks too complicated. There must be a better and easier way. And second : is there a way to dynamically import the class ?

class_name = "my_class_name"                # located in the module : my_class_name.py  
import my_class_name from my_class_name          

my_class = globals()[class_name]  
object = my_class()  
func = getattr开发者_如何学C(my_class,"my_method")
func(object, parms)                         # and finally calling the method with some parms


Take a look at the __import__ built-in function. It does exactly what you expect it to do.

Edit: as promised, here's an example. Not a very good one, I just kinda got bad news and my head is elsewhere, so you'd probably write a smarter one with more practical application for your context. At least, it illustrates the point.

>>> def getMethod(module, cls, method):
...     return getattr(getattr(__import__(module), cls), method)
... 
>>> getMethod('sys', 'stdin', 'write')
<built-in method write of file object at 0x7fcd518fa0c0>

Edit 2: here's a smarter one.

>>> def getMethod(path):
...     names = path.split('.')
...     return reduce(getattr, names[1:], __import__(names[0]))
... 
>>> getMethod('sys.stdin.write')
<built-in method write of file object at 0x7fdc7e0ca0c0>

Are you still around?

0

精彩评论

暂无评论...
验证码 换一张
取 消