Frank Vel
Frank Vel

Reputation: 1208

Adding methods in __init__() in Python

I'm making classes which are similar, but with different functions, depending on the use of the class.

class Cup:
    def __init__(self, content):
        self.content = content

    def spill(self):
        print(f"The {self.content} was spilled.")

    def drink(self):
        print(f"You drank the {self.content}.")

Coffee = Cup("coffee")
Coffee.spill()
> The coffee was spilled.

However, it is known during the initialization of an object whether or not the cup will be spilled or drank. If there are many cups, there's no need for all of them to have both functions, because only one of them will be used. How can I add a function during initialization?

Intuitively it should be something like this, but this apparently didn't work:

def spill(self):
    print(f"The {self.content} was spilled.")

class Cup:
    def __init__(self, content, function):
        self.content = content
        self.function = function

Coffee = Cup("coffee", spill)
Coffee.function()
> The coffee was spilled

Upvotes: 1

Views: 35

Answers (1)

Qeek
Qeek

Reputation: 1970

If you create a class in Python with methods e.g.

class A
    def method(self, param1, param)

It will make sure that when you call A().method(x,y) it fill the self parameter with instance of A. When you try specify method yourself outside of the class then you have to also make sure that the binding is done properly.

import functools
class Cup:
    def __init__(self, content, function):
        self.content = content
        self.function = functools.partial(function, self)

Upvotes: 2

Related Questions