我想我很容易用一个例子来解释这个问题 假设我想编写自己的矢量类。 在那个类中,我想说我想定义一个添加2个向量的方法 类似的东西:
class vector:
.....
def add(self,other):
----some code
所以基本上这样做是..如果一个向量是vec 然后
vec.add(othervec)
会做补充.. 但是我该怎么做 它就像是在加入你自己的类......数据类型 ? 感谢
答案 0 :(得分:3)
如果要添加两个类,我会查看__add__
函数,它允许您进行正常添加(而不是调用.add()
):
a + b
关于你的问题,我不确定你在问什么。我写了这样的Vector()
课:
class Vector:
def __init__(self, x = 0, y = 0, z = 0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
答案 1 :(得分:2)
在Python中,您应该使用duck typing,即根本不用担心类型:
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, othervec):
return Vector(self.x + othervec.x, self.y + othervec.y)
如果需要,可以让add
修改 Vector对象,而不是返回一个新对象。但是,这会使你的类变得可变,因此更难处理:
def add_mutable(self, othervec):
self.x += othervec.x
self.y += othervec.y
答案 2 :(得分:1)
当然,你可以完全按照你说的做,假设你想要添加/更改列表的功能
class Vector(list):
def add(self, v):
list.extend(self, v)
你可以像这样使用它:
> v = Vector([1,2,3])
> v.add([4,5,6])
> print v
> [1, 2, 3, 4, 5, 6]