简体   繁体   English

Python:如何防止范围内的长变量名

[英]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.

相关问题 如何使用python更改嵌套范围内的全局变量? - How do I change global variable in nested scope using python? 如何在python中为长名称选择合适的变量名称 - How to choose proper variable names for long names in python 在Python 2中,如何在父作用域中写入变量? - In Python 2, how do I write to variable in the parent scope? 给定Python中的变量名称列表,如何创建一个变量名称为键的字典(对于变量的值)? - Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)? 如何在超链接中使用变量名? - How do I use variable names in hyperlinks? python:如何捕获在非全局祖先外部作用域中声明的变量? - python: How do I capture a variable declared in a non global ancestral outer scope? 如何确定python中的整数变量是否具有超出范围的隐藏值? - How do I find out if a integer variable in python has an out of scope hidden value? 我有一个带有函数名称的字符串变量,如何在Python中调用该函数? - i have a string variable which comes with function names, how do I call the function in Python? 如何将相同的列表 object 分配给 python 中的两个不同变量名? - How do i assign same list object to two different variable names in python? 如何使用 python 从分组的 dataframe 中将图表名称作为变量插入? - How do I insert chart names as a variable from a grouped dataframe using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM