Python Tutorials :: class
<
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point(1, 1)
p2 = Point(2, 2)
p3 = p1 + p2
# p3.x is 3 and p3.y is 3
p3 += Point(3, 5)
# p3.x is 6 and p3.y is 8
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
return \
self.x < other.x and \
self.y < other.y
def __gt__(self, other):
return \
self.x > other.x and \
self.y > other.y
p1 = Point(1, 2)
p2 = Point(2, 3)
b1 = p1 > p2
# b1 is False
b2 = p1 < p2
# b2 is True
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __xor__(self, pow):
self.x = self.x ** pow
self.y = self.y ** pow
return self
p1 = Point(2, 3)
p1 = p1 ^ 3
# p1.x is 8 and p1.y is 27
p2 = Point(2, 3)
p2 ^ 2
# p2.x is 4 and p2.y is 9
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return \
self.x == other.x and \
self.y == other.y
def __ne__(self, other):
return \
self.x != other.x or \
self.y != other.y
p1 = Point(1, 1)
p2 = Point(2, 2)
p3 = Point(1, 1)
equal1 = p1 == p2
# equal1 is False
equal2 = p1 == p3
# equal2 is True
equal3 = p1 != p3
# equal3 is False
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __invert__(self):
self.x, self.y = self.y, self.x
p = Point(1, 3)
~p
# p.x is 3 and p.y is 1
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point(1, 1)
p2 = Point(2, 2)
p3 = p1 + p2
# p3.x is 3 and p3.y is 3
p3 += Point(3, 5)
# p3.x is 6 and p3.y is 8
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
return \
self.x < other.x and \
self.y < other.y
def __gt__(self, other):
return \
self.x > other.x and \
self.y > other.y
p1 = Point(1, 2)
p2 = Point(2, 3)
b1 = p1 > p2
# b1 is False
b2 = p1 < p2
# b2 is True
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __xor__(self, pow):
self.x = self.x ** pow
self.y = self.y ** pow
return self
p1 = Point(2, 3)
p1 = p1 ^ 3
# p1.x is 8 and p1.y is 27
p2 = Point(2, 3)
p2 ^ 2
# p2.x is 4 and p2.y is 9
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return \
self.x == other.x and \
self.y == other.y
def __ne__(self, other):
return \
self.x != other.x or \
self.y != other.y
p1 = Point(1, 1)
p2 = Point(2, 2)
p3 = Point(1, 1)
equal1 = p1 == p2
# equal1 is False
equal2 = p1 == p3
# equal2 is True
equal3 = p1 != p3
# equal3 is False
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __invert__(self):
self.x, self.y = self.y, self.x
p = Point(1, 3)
~p
# p.x is 3 and p.y is 1
No comments