Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining "boolness" of a class in python

Why doesn't this work as one may have naively expected?

class Foo(object):     def __init__(self):         self.bar = 3     def __bool__(self):         return self.bar > 10  foo = Foo()  if foo:     print 'x' else:     print 'y' 

(The output is x)

like image 904
wim Avatar asked Nov 20 '11 23:11

wim


People also ask

What is the definition of a class Python?

Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.

How do you define a class parameter in Python?

Python Class Object At first, you put the name of the new object which is followed by the assignment operator and the name of the class with parameters (as defined in the constructor). Remember, the number and type of parameters should be compatible with the parameters received in the constructor function.

What is contained in a Python class definition?

Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. Some points on Python class: Classes are created by keyword class.


1 Answers

For Python 2-3 compatibility, just add this to your example:

Foo.__nonzero__ = Foo.__bool__ 

or expand the original definition of Foo to include:

__nonzero__ = __bool__ 

You could of course define them in reverse too, where the method name is __nonzero__ and you assign it to __bool__, but I think the name __nonzero__ is just a legacy of the original C-ishness of Python's interpretation of objects as truthy or falsy based on their equivalence with zero. Just add the statement above and your code will work with Python 2.x, and will automatically work when you upgrade to Python 3.x (and eventually you an drop the assignment to __nonzero__).

like image 53
PaulMcG Avatar answered Nov 14 '22 06:11

PaulMcG