1

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

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.