
[英]How to give class parameter name to function to change this parameter
[英]How to give a class a referencable string name?
Scenerio是我正在使用arg解析器来获取命令行参数auth_application。
auth_application
命令可以具有许多值,例如:
cheese
eggs
noodles
pizza
这些值与可编程类有关。
我想要一种命名类的方法,可以使用装饰器。
所以我可以说
if auth_application is Cheese.__name__:
return Cheese()
当前,我维护一个auth_application
名称元组,并且必须将其公开给我的arg解析器类以及导入所需的类。
无论如何要使它更好? 是否为类命名装饰器?
我正在寻找python 2.7解决方案,但是了解python 3解决方案可能会很有用。
十分简单。
class command(object):
map = {}
def __init__(self, commandname):
self.name = commandname
def __call__(self, cls):
command.map[self.name] = cls
return cls
class NullCommand(object):
pass
@command('cheese')
class Cheese(object):
pass
@command('eggs')
class Eggs(object):
pass
def func(auth_application):
return command.map.get(auth_application, command.NullCommand)()
绝对可以! 您需要了解类属性 。
class NamedClass(object):
name = "Default"
class Cheese(NamedClass):
name = "Cheese"
print(Cheese.name)
> Cheese
您可以保留所有“允许的类”的清单,然后对其进行遍历以找到从命令行引用的类。
allow_classes = [Cheese,Eggs,Noodles,Pizza]
for cls in allow_classes:
if auth_application.lower() is cls.__name__.lower():
return cls()
您可以使用标准的Inspect库获取真实的类名称,而不必使用任何额外的数据来扩充您的类-即使您没有源代码,这也适用于任何模块中的任何类。
例如-列出mymodule中定义的所有类:
import mymodule
import inspect
for name, obj in inspect.getmembers(mymodule, inspect.isclass):
print name
obj变量是一个真实的类对象-您可以使用它声明实例,访问类方法等。
要通过类的名称字符串获取类的定义-您可以编写一个简单的搜索函数:
import mymodule
import inspect
def find_class(name):
"""Find a named class in mymodule"""
for this_name, _cls_ in inspect.getmembers(mymodule, inspect.isclass):
if this_name = name:
return _cls_
return None
....
# Create an instance of the class named in auth_application
find_class(auth_application)(args, kwargs)
注意:代码段未经测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.