0

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 Nones and not instances of class Foo. Why is this? What can I change to get the desired result?

type(updater(Foo())) #NoneType
2
  • 3
    You're not returning anything from Foo.update. Commented Jul 14, 2016 at 17:49
  • See my comment below on Dipak's answer Commented Jul 14, 2016 at 18:00

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

The first one is what I wanted. Why does splitting it up into two lines totally change the effect?
@Taylor Because then you're returning the object itself, not the return value of .update(), which is None.
yeah, makes sense. I feel stupid for not having run into this before.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.