簡體   English   中英

Python:如何將某個對象的命名空間導入當前命名空間?

[英]Python: how can I import the namespace of some object to current namespace?

我有一個Python類,它包含幾個嵌套的參數組:

class MyClass(object):
    #some code to set parameters

    def some_function(self):
        print self.big_parameter_group.small_parameter_group.param_1
        print self.big_parameter_group.small_parameter_group.param_2
        print self.big_parameter_group.small_parameter_group.param_3

我想減少訪問參數所需的代碼。 我應該在some_function的頂部放置什么來簡單地通過名稱訪問參數(param_1,param_2,param_3)? 我應該在MyClass中放置什么來為其所有方法應用此快捷方式,而不僅僅是some_function?

我會用它開始這個功能

spg = self.big_parameter_group.small_parameter_group

然后使用該縮寫。 你可以這樣定義的縮寫__init__()我想,如果你想用在任何地方使用他們self的前面。

一種方法是為每個屬性創建屬性:

@property
def param_1(self):
    return self.big_parameter_group.small_parameter_group.param_1
@property
def param_2(self):
    return self.big_parameter_group.small_parameter_group.param_2
@property
def param_2(self):
    return self.big_parameter_group.small_parameter_group.param_2

另一個更健壯但不太明確的方法是覆蓋getattr方法,如下所示:

def __getattr__(self, name):
    import re
    p = re.compile('param_[0-9]+')
    if p.match(name):
        return getattr(self.big_parameter_group.small_parameter_group, name)
    else:
        return super(MyClass, self).__getattr__(name)

這適用於與正則表達式指定的格式匹配的任何屬性( param_ [some number])

這兩種方法都允許你調用self.param_1等,但它只是用於重新審閱。 如果要設置屬性,還需要創建一個setter:

@param_1.setter
    def param_1(self, value): 
        print 'called setter'
        self.big_parameter_group.small_parameter_group.param_1 = value

或者補充getattr

def __setattr__(self, name, value):
    import re
    p = re.compile('param_[0-9]+')
    if p.match(name):
        return setattr(self.big_parameter_group.small_parameter_group, name, value)
    else:
        return super(MyClass, self).__setattr__(name, value)

(沒有測試過這些,所以可能有拼寫錯誤,但概念應該有效)

在您的初始化中,您可以隨時做到。

self.local_param_1 = self.big_parameter_group.small_parameter_group.param_1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM