Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define when a class is empty

Tags:

python

class

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")
like image 905
Zweedeend Avatar asked Sep 17 '13 11:09

Zweedeend


People also ask

Can we define a empty class?

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.

How do you declare an empty class?

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 you have an empty class in Java?

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.


2 Answers

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.

like image 157
poke Avatar answered Oct 22 '22 01:10

poke


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__
like image 33
phihag Avatar answered Oct 22 '22 01:10

phihag