[英]best practice regarding encapsulation python
I suspect that this will be a very remedial question but here goes: 我怀疑这将是一个非常补救的问题,但是这里有:
Frequently when I'm making new classes and methods within the class, I tend to make a lot of the variables that I would regard as fundamentally "local" in their function accessible from the outside by making them self.x instead of just plain old x for example. 通常,当我在该类中创建新的类和方法时,我倾向于通过使它们成为self.x而不是普通的旧变量,从而使许多我认为从根本上可以在其函数中“局部”访问的变量例如x。 I find this helpful for debugging (so that, for example if my end results are wonky I can go back to make sure that the contents of array x are what I think they are). 我发现这对调试很有帮助(例如,如果最终结果很奇怪,我可以返回以确保数组x的内容符合我的想法)。
This allows me the diagnostics I need during writing, but then I later have to go back and change all the self.x, self.y, etc.... back to plain old x, y, etc... so that when I later type the object name the list of stuff I get to choose from is managable. 这使我可以在编写过程中进行诊断,但是后来我不得不返回并更改所有self.x,self.y等...回到普通的旧x,y等...以便稍后我输入对象名称,可以管理的东西列表。
I suppose that this practice reflects my status as a beginner and I wonder what the mroe experienced guys are doing along this line. 我想这种做法反映了我作为初学者的身份,我想知道经验丰富的家伙在这方面正在做些什么。 I figure there must be a better way. 我认为必须有更好的方法。 Appreciate any tims or advice. 感谢任何tims或建议。
Encapsulation is actually a form of abstraction. 封装实际上是一种抽象形式。 What you want to achieve is to make it as easy as possible to work with the data and hide all the nitty-gritty details from the outside. 您想要实现的是使数据处理尽可能容易,并从外部隐藏所有细微的细节。 You want loosely coupled components . 您需要松散耦合的组件 。
Here are some tips: 这里有一些提示:
Despite all of that, just keep coding. 尽管如此,请继续编码。 You will get better at this over time. 随着时间的流逝,您会变得更好。 This just comes with experience. 这只是经验。 If you have some spare time to work on this, try Project Euler 如果您有空闲时间进行此工作,请尝试Euler项目
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.