[英]Python: How do I prevent long variable names in scope
I have stuff like: self.megacity.resourceloader.sound.mcintro.play()我有这样的东西:self.megacity.resourceloader.sound.mcintro.play()
Is there any elegant way to prevent such long stuff like this?有没有什么优雅的方法来防止这样长的东西? Some sort of structural change, perhaps?
也许是某种结构性变化?
Thanks.谢谢。
x = self.megacity.resourceloader.sound.mcintro
x.play()
Look up the Law of Demeter to help you find better ways to loosen coupling between components in your program:查看得墨忒耳定律以帮助您找到更好的方法来放松程序中组件之间的耦合:
When applied to object-oriented programs, the Law of Demeter can be more precisely called the “Law of Demeter for Functions/Methods” (LoD-F).
当应用于面向对象的程序时,迪米特法则可以更准确地称为“函数/方法的迪米特法则”(LoD-F)。 In this case, an object A can request a service (call a method) of an object instance B, but object A cannot "reach through" object B to access yet another object, C, to request its services.
在这种情况下,对象 A 可以请求对象实例 B 的服务(调用方法),但对象 A 不能“通过”对象 B 访问另一个对象 C,以请求其服务。 Doing so would mean that object A implicitly requires greater knowledge of object B's internal structure.
这样做意味着对象 A 隐含地需要对对象 B 的内部结构有更多的了解。 Instead, B's interface should be modified if necessary so it can directly serve object A's request, propagating it to any relevant subcomponents.
相反,B 的接口应该在必要时进行修改,以便它可以直接为对象 A 的请求提供服务,并将其传播到任何相关的子组件。 Alternatively, A might have a direct reference to object C and make the request directly to that.
或者,A 可能直接引用对象 C 并直接向该对象发出请求。 If the law is followed, only object B knows its own internal structure.
如果遵循规律,则只有对象 B 知道自己的内部结构。
Use the Facade pattern , eg:使用Facade 模式,例如:
class SoundPlayer:
def play_megacity(self):
return self.megacity.resourceloader.sound.mcintro.play()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.