简体   繁体   English

关于封装python的最佳实践

[英]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: 这里有一些提示:

  • Think about the right datastructures. 考虑正确的数据结构。 It should be close to the problem, easy to use and simple to implemement. 它应该接近问题,易于使用并且易于实现。
  • Avoid redundant code. 避免使用冗余代码。 One function for a single task. 一项任务的一项功能。 One class per module. 每个模块一节课。 This also increases code reuse. 这也增加了代码重用。
  • Think libraries not programs. 认为库不是程序。 Group related functions and modules together into libraries. 将相关功能和模块组合到库中。 The programs which use them should just glue the libraries together. 使用它们的程序应该将库粘合在一起。 Then you can improve the libraries separately from the main program and use the code for other projects as well. 然后,您可以与主程序分开改进库,并将代码也用于其他项目。
  • Avoid global state. 避免全局状态。 You don't want to have variables which are used all over the place and get modified in unexpected places. 您不想让变量在各处使用并在意想不到的地方被修改。 This will just cause headaches down the road. 这只会在以后引起头痛。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM