在实例中重写类的方法是否不好? [英] Is it a bad practice to override a method of a class in an instance?
问题描述
假设我写了一个元类 M
,而用户写了我的元类的实例 A
,它覆盖了方法 g
:>
Let’s say that I write a metaclass M
and a user writes an instance A
of my metaclass which overrides a method g
:
>>> class M(type):
... def f(self): return self.g()
... def g(self): return 'foo'
...
>>> class A(metaclass=M):
... def g(self): return 'bar'
...
>>> A.f() # oops!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
TypeError: g() missing 1 required positional argument: 'self'
>>> del A.g
>>> A.f()
'foo'
或者说我写了一个类 A
,而用户写了一个我的类的实例 a
,它覆盖了方法 g
:
Or let’s say that I write a class A
and a user writes an instance a
of my class which overrides a method g
:
>>> class A:
... def f(self): return self.g()
... def g(self): return 'foo'
...
>>> a = A()
>>> a.g = lambda self: 'bar'
>>> a.f() # oops!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
TypeError: <lambda>() missing 1 required positional argument: 'self'
>>> del a.g
>>> a.f()
'foo'
在实例中重写类的方法是否是错误的做法?
Is it a bad practice to override a method of a class in an instance?
推荐答案
在极少数情况下必须使用猴子补丁作为最后手段的情况往往是无法访问源代码来实现的情况适当的解决方案,或者无法以某种方式定义希望修复或扩展的类的子类.
The rare cases in which monkey-patching has to be used as a last resort tend to be cases where you don't have access to the source code to implement a proper solution, or where you're somehow unable to define a subclass of the class you're hoping to fix or extend.
在大多数其他情况下,这是一种不好的做法,通常是代码库中的不得已而为之,当它不试图修复您没有代码的第三方解决方案时,它就会承担太多错误的设计决策.
It's a bad practice in most other cases and often a final resort in a codebase that has become burdened with too many bad design decisions, when it's not trying to fix a third party solution for which you don't have the code.
这篇关于在实例中重写类的方法是否不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!