Is it possible to delete a method from an object (not class) in python?

前端 未结 8 1745
借酒劲吻你
借酒劲吻你 2020-12-31 13:24

I have a class with a few methods, some of which are only valid when the object is in a particular state. I would like to have the methods simply not be bound to the objects

8条回答
  •  执念已碎
    2020-12-31 14:01

    As an additional possibility (twisting the question a little bit), if it makes more sense to only have certain methods on certain instances, you can always add those methods in the __init__ of the class to those instances for which it makes sense. Ex: say we have your Wizard class, and the only time a Wizard instance should have the domagic() method is if a magic parameter passed to __init__() is True. We could then do something like:

    class Wizard(object):
        def __init__(self, magic = False):
            if magic:
                def _domagic():
                    print "DOING MAGIC!"
                self.domagic = _domagic
    
    def main():
        mage = Wizard(magic = True)
        nomage = Wizard(magic = False)
    
        mage.domagic()      # prints "DOING MAGIC!"
        nomage.domagic()    # throws an AttributeError
    

    Having said that, this code does have a bit of smell to it -- now before you call domagic() on a Wizard, you need to know if the method is defined or not. I wonder if the inheritance heirarchy could be refined a bit to make this a bit more elegant.

提交回复
热议问题