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?

aschultz
  • 1,608
  • 3
  • 17
  • 28
mishlke
  • 53
  • 5

3 Answers3

2

You need to use self.m()

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

    def m(self):
        print('2')
        print('3')
Iain Shelvington
  • 26,159
  • 1
  • 24
  • 40
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().

Karl Knechtel
  • 56,349
  • 8
  • 83
  • 124
-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()

Sazzy
  • 1,764
  • 3
  • 19
  • 24