Python:如何将某个对象的名称空间导入到当前名称空间?
我有一个 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 ?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会以 开始该函数
,然后使用该缩写。我想,如果您想在前面带有
self
的任何地方使用它们,您可以在__init__()
中定义这样的缩写。I would start the function with
and then use that abbreviation. You could define abbreviations like this in
__init__()
, I suppose, if you wanted to use them everywhere withself
on the front.一种方法是为每个属性创建属性:
另一种更强大但不太明确的方法是重写 getattr 方法,如下所示:
这适用于与正则表达式指定的格式匹配的任何属性(
param_
[some number])这两种方法都允许您调用
self.param_1
等,但它只是用于检索。如果你想设置属性,你还需要创建一个setter:或者补充
getattr
:(还没有测试这些,所以可能会有拼写错误,但这个概念应该可行)
One way is to create properties for each of them:
Another more robust but less explicit way would be to override the getattr method like so:
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:Or to complement
getattr
:(Haven't tested these out so there may be typos but the concept should work)
在你的 init 内部你总是可以这样做。
Inside your init you could always do.