Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it best-practice to place __init__ in the beginning or end of a class?

Consider the following code:

class AClass():

    def defaultMethod(self):
        return 1

    def __init__(self, methodToUse = defaultMethod):
        print (methodToUse(self))

if __name__== "__main__":
    AClass()

In this case one cannot move the defaultMethod below the __init__ method, if I do, it causes "NameError: name 'defaultMethod' is not defined"

This means that I need to define this method before the __init__ or else Python does not know about it. This again, means that I no longer have __init__ as the first method, which leaves me to wonder whether it is usual to place the __init__ method at the end of a class or in the beginning.

like image 237
David Avatar asked Oct 19 '25 06:10

David


2 Answers

What do you mean, "I need to define this method before the init or else Python does not know about it" ?

>>> class A(object):
...     def __init__(self):
...         self.foo()
...     def foo(self):
...         print '42'
... 
>>> A()
42

I usually place __ init__() before other instance methods, but after class methods/property/attributes.

like image 86
Marco Mariani Avatar answered Oct 21 '25 21:10

Marco Mariani


I think you're doing things a little peculiarly. You should still put __init__ high up if not the first method. Readability is key and __init__ exposes what you expect the main instance fields to be.

Here are three alternatives. My preference is for the first as it documents the default method and will require the least modification to your code. The last works, but could be confusing for anyone having to maintain your code.

class A(object):
    def __init__(self, method="foo"):
        if callable(method):
            method(self)
        else:
            getattr(self, method)()
    def foo(self):
        print "something"


class B(object):
    def __init__(self, method = None):
        if method is None:
            self.defaultMethod()
        else:
            method(self)
    def defaultMethod(self):
        print "foo"


def _defaultMethod(self):
    print self.x

class C(object):
    def __init__(self, method = _defaultMethod):
        self.x = "bleh"
        method(self)
    def anotherMethod(self):
        print "doing something else"
    def defaultMethodProxy(self):
        _defaultMethod(self)
like image 23
Dunes Avatar answered Oct 21 '25 19:10

Dunes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!