Where should I define the functions that I use in __init__

I am writing a class that uses some functions inside its function __init__, and I am not sure about the best practice of defining these functions. Usually I usually need to define __init__, but if I need to use a function / method in __init__, then I need to define it first. I don’t want to define it outside the class as useless outside the class, but it seems useless to me to define methods before __init__. What are the normal conventions for this?

+5
source share
4 answers

Just add methods to your class like any other method

class Test(object):
    def __init__(self):
        self.hi()

    def hi(self):
        print "Hi!"

No problems.

Python, __init__ .

+12

__init__ . , . Python:

- . ( ). , .

; .

+3

__init__ , , __init__ .

class A:
    def __init__(self):
        print self.x()

    def x(self):
        return 10
+1

Why should it be dirty to define methods after init? Think of it this way:

When you define

class MyClass(object):

    def __init__(self):
        self.something = whatever
        self.do_something_else()

    def do_something_else(self):
        ...

__init__- this is the method of your class MyClass, like do_something; this is only the first class method that will be called when the instance is created MyClass. So, first put __init__not only ordinary, but also logical.

Your method do_something_elseshould not be defined first, because you use it in __init__. In terms of MyClass, this is a method similar to another. When you create your instance myclass=MyClass()is do_something_elsealready defined ...

0
source

All Articles