简体   繁体   中英

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

I have a Python class, which contains several nested parameter groups:

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

I want to reduce code needed to access parameters. What should I place at the top of some_function to access the parameters simply by their names (param_1, param_2, param_3)? And what should I place somewhere in MyClass to apply this shortcut for all its methods, not only some_function?

I would start the function with

spg = self.big_parameter_group.small_parameter_group

and then use that abbreviation. You could define abbreviations like this in __init__() , I suppose, if you wanted to use them everywhere with self on the front.

One way is to create properties for each of them:

@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

Another more robust but less explicit way would be to override the getattr method like so:

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)

This will work for any property that matches the format specified by the regex ( param_ [some number])

Both of these methods will allow you to call self.param_1 etc, but it's just for retriving. If you want to set the attributes you'll need to also create a setter:

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

Or to complement 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)

(Haven't tested these out so there may be typos but the concept should work)

在您的初始化中,您可以随时做到。

self.local_param_1 = self.big_parameter_group.small_parameter_group.param_1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM