[英]What's the correct way to access methods of a member variable in a class pointing to an object?
What's the correct way to define/access methods of a member variable in a class pointing to an object? 在指向对象的类中定义/访问成员变量的方法的正确方法是什么?
For example, I have a class Foo
that has a method foo_method
: 例如,我有一个具有方法foo_method
Foo
类:
class Foo:
def foo_method(self):
return 'bar'
Now, in another class Bar
, I'd like to store an object to this class (I do not want Bar
to inherit Foo
). 现在,在另一个类Bar
,我想将一个对象存储到此类(我不希望Bar
继承Foo
)。
What is the correct/recommended way to define class Bar
? 定义Bar
类的正确/推荐方法是什么?
class Bar:
def __init__(self):
self.foo = Foo()
# OR
class Bar:
def __init__(self):
self.foo = Foo()
def bar_method(self):
return self.foo.bar()
The former will allow me to use: 前者将允许我使用:
x = Bar()
x.foo.foo_method()
But, with this I'm directly accessing methods of a member variable (strong coupling). 但是,与此同时,我直接访问成员变量的方法(强耦合)。
The benefits I see with this approach are: 我看到的这种方法的好处是:
Foo
. 我不必包装添加到Foo
类的每个新方法。 Bar
may contain more member variables pointing to other classes. Bar
可能包含更多指向其他类的成员变量。 Not wrapping them keeps Bar
smaller and manageable in size. 不包裹它们可使Bar
变得更小且易于管理。 bar
like a menu ( x.foo
) followed by a sub-menu ( x.foo.foo_method()
, x.bar.foobar()
, etc.) making it easier to develop code. 从IDE(PyCharm等)或IPython的自动补全功能帮助检查bar
就像一个菜单( x.foo
),后跟一个子菜单( x.foo.foo_method()
x.bar.foobar()
等。)使其更易于开发代码。 The cons are strong coupling, not encapsulating internal details of foo
, etc. 缺点是很强的耦合,没有封装foo
等内部细节。
I wanted to check if this a recommended practice? 我想检查一下这是否是推荐做法? And/or if there are any guidelines related to this (kind of implementing a composite pattern)? 和/或是否有与此相关的准则(实施复合模式)?
Any inputs/pointers will be highly appreciated! 任何输入/指针将不胜感激!
There are no real guidelines, but if you make a bar_method()
that explicitly calls foo.bar()
and does nothing in between it's the exact same coupling and less convenient. 没有真正的指导原则,但是如果您创建一个bar_method()
来显式调用foo.bar()
且在两者之间不执行任何操作,则这是完全相同的耦合,并且不太方便。
Python's idioms include " We are all responsible users " and in that case, when encapsulation does not provide you any benefit, I personally wouldn't use proxy functions. Python的习惯用法包括“ 我们都是负责任的用户 ”,在这种情况下,如果封装没有给您带来任何好处,我个人就不会使用代理功能。 Leaving it as is results in smaller code which is easier to maintain and is more accessible. 保留原样将导致更小的代码,更易于维护和访问。 Auto-completion as you mentioned is just an added bonus. 您提到的自动完成只是一项额外的奖励。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.