我可以在不使用Python创建新类的情况下覆盖类函数吗? [英] Can I override a class function without creating a new class in Python?
问题描述
我正在pygame中制作游戏,我做了一个抽象"类,唯一的工作是将给定关卡的sprite存储(目的是将这些关卡对象存储在列表中,以方便玩家移动)从一个级别到另一个级别)
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)
好的,这个问题.如果我能在Python中做到这一点(Java的代码致谢):
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.
因此,在一位更坚强的开发人员继续研究这种反Python的方式之前(我已经读了很多本网站的内容,以便从Python专家那里获得共鸣),只是告诉我它是否可行.
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.
推荐答案
是的,可以!
class Foo(object):
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()
f.do_other()
g.do_foo()
g.do_other()
因此,在一位更坚强的开发人员继续探讨这可能是如何反Python之前
So, before one of the more stanch developers goes on about how anti-python this might be
以这种方式覆盖函数(如果您有充分的理由这么做)在我看来似乎很Python化.一个可能需要这样做的原因/方式的示例是,如果您拥有一个动态功能,而静态继承不适用或不适用.
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.
反对的案例可能在Python的Zen中找到:
The case against might be found in the Zen of Python:
- 美丽胜于丑陋.
- 可读性计数.
- 如果难以解释实现方式,那是个坏主意.
这篇关于我可以在不使用Python创建新类的情况下覆盖类函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!