【发布时间】:2013-01-01 16:41:16
【问题描述】:
使用__class__ 在类中创建新实例是个好主意吗?
以下代码是这样做的示例:
from collections import namedtuple
_Position = namedtuple('Position', ['x', 'y'])
class Position(_Position):
def __add__(self, other):
return __class__(self.x + other.x, self.y + other.y)
对我来说,使用实际的类名听起来像是重复的代码。如果类的名称发生更改,我必须在所有情况下都更改它,即使现代 IDE 可以为您做到这一点。
顺便说一句。 __class__ 是什么变量?你不应该只能通过self. 访问它吗?
【问题讨论】:
-
如果你要继承
namedtuple,为什么不从头开始创建一个对象? -
这里有一个很好的解释:stackoverflow.com/questions/8060751/…
-
@Blender 这只是一个例子。我确实可以从头开始创建一个对象。
标签: python python-3.x code-duplication