开发者

What code in a class should be belongs in the constructor, method

I'm new to oop and was trying to understand where the appropriate location to 开发者_如何学Pythonput code in a class is. So far as I understand there's three main areas you can put your code:

  • At the beginning of the class (Ex. Instance variables declared at the class level outside of the constructor or methods)
  • In the Constructor
  • In the Method

What is protocol as far as the type/kinds of code that should go in each of those sections?


  • Attributes should only define static or const values directly. Other values can be defined in constructor/methods.
  • The constructor should only define values that are required for the class/object to work properly (you can also call methods from the constructor).
  • Methods can define everthing else.
  • There is also a destructor.


It's kind of up to you. Different patterns / design standards dictate different approaches. Usually, a constructor only 'asks' for the things essential to the object (like a database connection), and store that in properties of the object. In any case, you want to keep your constructor small, and as flexible as possible - you never know in which ways you might use the object in the future! So, while for instance it might seem like a good idea at this time to load some data from your database in the constructor, it's usually better to put these kinds of things in methods, so they can be skipped at will later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜