2015-09-22 59 views
0

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解決方案可能對您有所幫助。

+1

你可以用像'classes = {'cheese'這樣的字典:奶酪,'雞蛋':雞蛋}'? – TigerhawkT3

+0

這基本上就是我所擁有的。我試圖減少需要的步驟/使維護更容易(更少的步驟) – visc

+0

我有一個元組('cheese','egg'...)和一堆if語句 – visc

回答

0

絕對可以!您需要了解class attributes

class NamedClass(object): 
    name = "Default" 

class Cheese(NamedClass): 
    name = "Cheese" 

print(Cheese.name) 
> Cheese 
0

你可以只保留你的所有「允許類」的名單的單層和迭代,要找到類被命令行參考。

allow_classes = [Cheese,Eggs,Noodles,Pizza] 

for cls in allow_classes: 
    if auth_application.lower() is cls.__name__.lower(): 
     return cls() 
1

容易心慌。

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)() 
0

您可以使用標準的Inspect Library才能獲得真正的類名,而無需任何額外的數據,以增加你的類 - 這適用於任何階層,任何模塊中 - 即使你沒有源代碼。

例如 - 要列出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) 

注:代碼片段沒有測試

相關問題