Reputation: 2085
I have a class and a function that tries to update and return instances of this class:
class Foo:
def __init__(self):
self.datum = 'a'
def update(self):
self.datum = 'b' if self.datum == 'a' else 'a'
def updater(foo_obj):
return( foo_obj.update() )
but calling updater()
returns None
s and not instances of class Foo
. Why is this? What can I change to get the desired result?
type(updater(Foo())) #NoneType
Upvotes: 0
Views: 315
Reputation: 388
If you'd like update
to return instances of the Foo
class, you have to explicitly have it do so with a return statement, otherwise it will implicitly return None
(i.e. it's a void method, even though Python doesn't use these terms because duck-typing). Do this like so:
def update(self):
self.datum = 'b' if self.datum == 'a' else 'a'
return self
You could also return the Foo
object in updater
if you don't want your class to do it, like so:
def updater(foo_obj):
foo_obj.update()
return foo_obj
If you'd like to return just self.datum
and not the whole object, then do that like:
def update(self):
self.datum = 'b' if self.datum == 'a' else 'a'
return self.datum
or similarly:
def updater(foo_obj):
foo_obj.update()
return foo_obj.datum
Upvotes: 0
Reputation: 6970
Update method updater.
def updater(foo_obj):
foo_obj.update()
return( foo_obj )
OR return self
from class function:
def update(self):
self.datum = 'b' if self.datum == 'a' else 'a'
return self
Upvotes: 1
Reputation: 311723
Your update
method does not return anything, which in Python means that it implicitly returns None
. If you want it to have a meaningful return value, you'd have to do so explicitly. E.g.:
def update(self):
self.datum = 'b' if self.datum == 'a' else 'a'
return self.datum
Upvotes: 1