Home > OS >  Is it good practice to initalize class instance inside class method?
Is it good practice to initalize class instance inside class method?

Time:10-28

Is it correct to define class instance inside a method? what are (if any) the pro and cons of doing this:


class Individual:
    def __init__(self, a_number):
        self.a_number = a_number

    def calculate_something(self):
        self.b_number = 2
        self.b_number  = 3

Instead of doing:


class Individual:
    def __init__(self, a_number):
        self.a_number = a_number
        self.b_number = 2

    def calculate_something(self):
        self.b_number  = 3

Edit: let's assume I call calculate_something() only once so that the output of the two snippets does not change (b_number can not go higher then 5 in the second snippet)

CodePudding user response:

The purpose of __init__ is to make your object ready for use. Is an instance of Individual usable without the b_number attribute set? If not, then you should initialize it in __init__. (If it is, it's still probably a good idea to initialize it, but you should ask yourself why b_number is an instance attribute in the first place.)

By "useable", I don't mean making assumptions about which methods a user might call immediately. Sure, maybe some methods don't require b_number, but if any do, you should assume someone might use before some other method has a chance to initialize the value. __init__ is special in that it is "guaranteed" to be called before any other instance method might be called (ignoring the use of __new__, anyway. Not that __new__ is an instance method, but it could technically call some other instance method on a new object before it is returned and passed to __init__.)

CodePudding user response:

So, you are trying to initialize the attribute in methods from the above piece of code. As you know init() dunder init. When a new object is made, this method is called to perform the task assigning the value to attributes or others, an object is passed as self, and other arguments to the class are passed after self.

In this case, is it good practice to initialize the class/instance attribute in the method? The answer depends on the need of the program. If a need of the program is to initialize attributes at the time of object creation and there is no need to take input from the user then one can do this.

  • Related