I've got two classes I'm testing to learn about how to use any() and all() with my own classes. Basically I have a class called Wrapped that has a member "self.members" which is a python list of class instances of another class called Unit. I've set up Unit so it defines a function called __bool__(self) like this:
Code:
def __bool__(self):
print "__bool__", self.a # simply here to confirm __bool__ is called by all()
if self.a is None:
return False
else:
return True
basically "self.a" in a Unit is just going to be an integer or it could be a None if the Unit() constructor was run with no argument. So this is the Unit class:
Code:
class Unit(object):
def __init__(self, a=None):
self.a = a
def __eq__(self, other):
return self.a == other.a
def __lt__(self, other):
return self.a < other.a
# any Unit that had a valid 'a' value set is considered good
def __bool__(self):
print "__bool__", self.a # check any() and all()
if self.a is None:
return False
else:
return True
and the Wrapped class is:
Code:
class Wrapped(object):
def __init__(self, mem=None):
if mem is None:
self.members = []
else:
self.members = [mem]
def add_member(self, mem=None):
if mem is not None:
self.members.append(mem)
def __len__(self):
return len(self.members)
def __bool__(self):
print "Wrapped __bool__"
if self.members:
return True
else:
return False
def __str__(self):
return ''.join([ s.__str__() + ' ' for s in self.members ])
So in a Unit instance with self.a of None case the __bool__() is False otherwise it's simply True (even a self.a of 0 will be True)
When I create a Wrapper instance and load it up with Units I have something unexpected:
Code:
foo = Wrapper()
foo.add_member(Unit(3))
foo.add_member(Unit())
foo.add_member(Unit(12))
print foo
print "all: " + str(all(foo.members))
The "print foo" shows what I expect via the __str__() in my Wrapped class :
Quote:
|
Unit() 3 Unit() None Unit() 12
|
But the "print "all: " + str(all(foo.members))" comes up unexpectedly:
I would have expected all(foo.members) to be False since that 2nd class had a None for the "a", plus I also see that the all() doesn't seem to call the Unit.__bool__() anyway because my test "print" doesn't show. I was thinking the all() function always has to use __bool__ from the class in the list?