简体   繁体   中英

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. 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).

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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