0

I'm learning about classes and design in Python, and I have a question of how to implement the following pattern:

I would like the class to initialise with some code, some of which I would like to be able to call later on via a function, e.g.:

class c:
    def __init__(self):
        print('1')
        m()

    def m(self):
        print('2')
        print('3')

I am after something like the above, but I cannot use m() in init as it will not have been declared at this point. Is there anyway of implementing this without having to use the same code twice?

3 Answers 3

2

You need to use self.m()

class c:
    def __init__(self):
        print('1')
        self.m()

    def m(self):
        print('2')
        print('3')
Sign up to request clarification or add additional context in comments.

Comments

2

cannot use m() in init as it will not have been declared at this point

This is not the case. Python's execution does not work that way; it will not care where the m definition is until it is actually needed.

The reason you got an error is because there is no "implicit this" in Python; writing m here looks for the global m and not a method m belonging to the instance. Just as you must accept an explicit self parameter, so you must explicitly look for methods on self: thus, self.m().

Comments

-1

You may be looking at @staticmethod or @classmethod decorators.

class c:
    def __init__(self):
        print('1')
        m()

    @staticmethod
    def m():
        # You don't rely on any class method initialised attributes
        print('2')
        print('3')

    @classmethod
    def m(cls):
        # You may use cls to refer to the class itself
        print('2')
        print('3')

You can choose which suits your case better for your particular method.

Both would allow you to call a function as c.m()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.