Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override a class function without creating a new class in Python?

I'm making a game in pygame and I have made an 'abstract' class that's sole job is to store the sprites for a given level (with the intent of having these level objects in a list to facilitate the player being moved from one level to another)

Alright, so to the question. If I can do the equivalent of this in Python(code curtesy of Java):

Object object = new Object (){
    public void overriddenFunction(){
        //new functionality
        };
    };

Than when I build the levels in the game I would simply have to override the constructor (or a class/instance method that is responsible for building the level) with the information on where the sprites go, because making a new class for every level in the game isn't that elegant of an answer. Alternatively I would have to make methods within the level class that would then build the level once a level object is instantiated, placing the sprites as needed.

So, before one of the more stanch developers goes on about how anti-python this might be (I've read enough of this site to get that vibe from Python experts) just tell me if its doable.

like image 911
Mikodite Yvette Avatar asked Jul 20 '13 00:07

Mikodite Yvette


1 Answers

Yes, you can!

class Foo:
    def do_other(self):
        print('other!')
    def do_foo(self):
        print('foo!')


def do_baz():
    print('baz!')

def do_bar(self):
    print('bar!')

# Class-wide impact
Foo.do_foo = do_bar
f = Foo()
g = Foo()
# Instance-wide impact
g.do_other = do_baz

f.do_foo()  # prints "bar!"
f.do_other()  # prints "other!"

g.do_foo()  # prints "bar!"
g.do_other()  # prints "baz!"

So, before one of the more stanch developers goes on about how anti-python this might be

Overwriting functions in this fashion (if you have a good reason to do so) seems reasonably pythonic to me. An example of one reason/way for which you might have to do this would be if you had a dynamic feature for which static inheritance didn't or couldn't apply.

The case against might be found in the Zen of Python:

  • Beautiful is better than ugly.
  • Readability counts.
  • If the implementation is hard to explain, it's a bad idea.
like image 133
Brian Cain Avatar answered Oct 13 '22 11:10

Brian Cain