Python:如何防止scop中的长变量名

2024-09-26 22:10:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的东西: self.megacity.resourceloader.声音.mcintro.play()

有没有什么优雅的方法来防止这样长的事情? 也许是某种结构上的改变?在

谢谢。在


Tags: 方法self声音play事情结构resourceloadermegacity
3条回答

查找Law of Demeter以帮助您找到更好的方法来松开程序中组件之间的耦合:

When applied to object-oriented programs, the Law of Demeter can be more precisely called the “Law of Demeter for Functions/Methods” (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. Doing so would mean that object A implicitly requires greater knowledge of object B's internal structure. Instead, B's interface should be modified if necessary so it can directly serve object A's request, propagating it to any relevant subcomponents. Alternatively, A might have a direct reference to object C and make the request directly to that. If the law is followed, only object B knows its own internal structure.

x = self.megacity.resourceloader.sound.mcintro
x.play()

使用门面http://en.wikipedia.org/wiki/Facade_pattern

class SoundPlayer:
        def PlayMegacity (target):
              target.megacity.resourceloader.sound.mcintro.play()

相关问题 更多 >

    热门问题