Reputation: 355
In the following example:
class Example(dict):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
ex = Example('ex')
if ex:
print(ex.get_name())
The if ex
statement is evaluating to False
and I am not getting any output. What is causing this instance to evaluate to False
?
Upvotes: 2
Views: 727
Reputation: 477794
You inherit from dict
. The truthiness of a dictionary (like almost every collection) depends on whether it contains elements. This holds for lists, sets, dictionaries and strings (a string is sometimes seen as an ordered collection of characters). Furthermore a lot of libraries have collections that follow the same rules (like counters, etc.).
You construct a dictionary here that does not contain any elements. So the truthiness is False
.
You can however override the truthiness again, with:
class Example(dict):
def __init__(self, name):
self.name = name
def __bool__(self):
return True
def get_name(self):
return self.name
Note that whether you find the truthiness of such Example(..)
with an underlying empty dictionary is a decision you have to make yourself (and of course it is better to follow "Python's guidelines). So the above code fragment is not per se correct for your application. It depends on what you want to do with it.
Furthermore it can be useful to pass additional unnamed arguments (*args
) and named arguments (**kwargs
) to the dictionary constructor to add elements to the underlying dictionary immediately as well as modifying the __repr__
and/or __str__
functions.
class Example(dict):
def __init__(self, name,*args,**kwargs):
super().__init__(*args,**kwargs)
self.name = name
def __bool__(self):
return True
def get_name(self):
return self.name
Upvotes: 7