How to determine when a class is empty

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 determine that V (0,0) is an empty vector, such that it will 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") 
+6
source share
3 answers

Define __bool__ , for example:

 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__ 
+6
source

You can implement the special __bool__ method:

 def __bool__ (self): return self.x != 0 or self.y != 0 

Note that in Python 2, a special method is called __nonzero__ .

Alternatively, since you have a vector, it may make even more sense to implement __len__ and provide the actual vector instead. If __bool__ not defined, Python will automatically try to use the __len__ method to get the length and evaluate if it is null.

+12
source

If you're just worried about getting out. Just add the __str__ method.

 def __str__( self ): if self.x and self.y : return "V({x},{y})".format( x = self.x, y = self.y ) else: return "Vector is empty" v = V( 0, 0 ) u = V( 1, 2 ) print v print u 

The output will be:

Vector is empty

In (1,2)

+1
source

Source: https://habr.com/ru/post/953976/


All Articles