中村 のりつぐ です。
In article <200203301456.g2UEue724321@...>
kikwai@... (機械伯爵) wrote:
> つまり、class Aで__add__を実装すると、A+Xの処理の仕方(ふるまい)
> が定義でき、__radd__を実装すると、X+Aのふるまいが定義できるだけです。
例を作ってみました。確かに Python の方が魂を渡している
分だけ簡単かも…。(Ruby の記述が正しいのか良く分からないけど)
# for Python
class Point:
def __init__(self, x, y):
self.x = x; self.y = y
def __add__(self, other):
try:
return Point(self.x + other.x, self.y + other.y)
except:
return Point(self.x + other, self.y + other)
def __radd__(self, other):
return Point(self.x + other, self.y + other)
def __repr__(self):
return "(%d,%d)" % (self.x, self.y)
p1 = Point(1, 1); print p1 # => (1,1)
p2 = Point(2, 2); print p2 # => (2,2)
print p1 + p2 # => (3,3)
p3 = p1 + 2; print p3 # => (3,3)
p3 = 2 + p1; print p3 # => (3,3)
# for Ruby
class Point
def initialize(x, y)
@x = x; @y = y
end
def +(other)
case other
when Point
Point.new(@x + other.x, @x + other.y)
when Numeric
Point.new(@x + other, @x + other)
else
p1, p2 = other.coerce(self)
return p1 + p2
end
end
def inspect
return "(%d,%d)" % [@x, @y]
end
def coerce(other)
case other
when Numeric
return Point.new(other, other), self
end
end
attr_reader :x, :y
end
p1 = Point.new(1, 1); p p1 # => (1,1)
p2 = Point.new(2, 2); p p2 # => (2,2)
p(p1 + p2) # => (3,3)
p3 = p1 + 2; p p3 # => (3,3)
p3 = 2 + p1; p p3 # => (3,3)
中村 典嗣 E-mail: nnakamur@...