本文介绍了在实例级别覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中有没有办法在实例级别覆盖类方法?例如:

Is there a way in Python to override a class method at instance level?For example:

class Dog:
    def bark(self):
        print "WOOF"

boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!

推荐答案

请不要如图所示这样做.当您对实例进行猴子补丁以使其与类不同时,您的代码变得不可读.

Please do not do this as shown. You code becomes unreadable when you monkeypatch an instance to be different from the class.

你不能调试monkeypatched代码.

You cannot debug monkeypatched code.

当您在 bobyprint type(boby) 中发现错误时,您会看到 (a) 它是一只狗,但是 (b) 对于一些晦涩的原因是它没有正确吠叫.这是一场噩梦.不要这样做.

When you find a bug in boby and print type(boby), you'll see that (a) it's a Dog, but (b) for some obscure reason it doesn't bark correctly. This is a nightmare. Do not do it.

请改为这样做.

class Dog:
    def bark(self):
        print "WOOF"

class BobyDog( Dog ):
    def bark( self ):
        print "WoOoOoF!!"

otherDog= Dog()
otherDog.bark() # WOOF

boby = BobyDog()
boby.bark() # WoOoOoF!!

这篇关于在实例级别覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 03:09