I wrote my own vector class:
#! /usr/bin/env python3
class V:
"""Defines a 2D vector"""
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self,other):
newx = self.x + other.x
newy = self.y + other.y
return V(newx,newy)
def __sub__(self,other):
newx = self.x - other.x
newy = self.y - other.y
return V(newx,newy)
def __str__(self):
return "V({x},{y})".format(x=self.x,y=self.y)
I want to define that V(0,0) is an empty vector, such that this would work: (The first case should return "Vector is empty")
v = V(0,0)
u = V(1,2)
if u:
print (u)
else:
print("Vector is empty")
if v:
print(v)
else:
print("Vector is empty")
Empty class: It is a class that does not contain any data members (e.g. int a, float b, char c, and string d, etc.) However, an empty class may contain member functions.
In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement.
Can I have an empty class? Is it bad programming practice? And if so, what can I implement instead? "Can I have an empty Java class?" - Yes.
You can implement the special method __bool__
:
def __bool__ (self):
return self.x != 0 or self.y != 0
Note that in Python 2, the special method is named __nonzero__
.
Alternatively, because you have a vector, it might make even more sense to implement __len__
and provide the actual vector length instead. If __bool__
is not defined, Python will automatically try to use the __len__
method to get the length and evaluate if it’s not zero.
Define __bool__
, like this:
class V:
"""Defines a 2D vector"""
def __init__(self,x,y):
self.x = x
self.y = y
def __bool__(self):
return self.x != 0 or self.y != 0
# Python 2 compatibility
__nonzero__ = __bool__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With