简体   繁体   中英

Slighly alter method by passing function to class constructor in Python

I'm writing a class which needs to use slightly different code depending on the instance.

I could achieve this through inheritance, but I wondered whether it would would be simpler to do this by passing a function to constructor when an instance is instantiated.

I'm thinking something like this:

class myClass():

    def __init__(self, fn):
        self.myProperty = 1
        self.instanceSpecificFunction = fn

    def myMethod(self):

        #Do things here that are common to all instances of class

        #[common code would be here]

        #But then run some code that is specific to this instance of the class
        self.instanceSpecificFunction(self)

def functionThatsSpecificToThisInstance(self):

    #In general, this code would want 
    #to be different if we instantiated a different instance

    self.myProperty = 3

myInstance = myClass(functionThatsSpecificToThisInstance)  

myInstance.myMethod()

Is this a terrible idea? Does this kind of design pattern have a name? If so is there a 'best' way to this?

Thanks very much,

Robin

Actually, I don't like the idea much.

First of all, you'll have random functions not belonging to any class in particular but that actually use self as arguments (although self is just a normal function argument, that's something in the code that doesn't smell very good ).

Having functions wandering around in a module usually makes me uncomfortable, unless the module is just a helper module filled only with helper functions . But mixing classes and functions and these functions actually performing some work on classes' instances is kind of messy from my point of view.

Inheritance looks great here. Just redefine a different constructor for every class that needs it and, when other developers see the code they will have a better idea of what's going on. At the end of the day you need to code the logic for those functions, so why not just code it inside the classes their instances represent .

Also, you may want to take a look to the Factory Pattern . It is a creational pattern that might fill your needs. The idea you have makes sense, but the implementation is rather messy. By following a pattern you make sure to take the rights step to create nice code, understandable and reusable. Take also a look at several creational patterns , maybe one of them is what you're looking for.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM