Simon
Simon

Reputation: 11

Call class method or return None

I am struggling with database relationships and Django, but have simplified my case drastically in order to get to the point.

I have the following class:

class Car(object):
    owner = 'No owner'

    def get_owner(self):
        return self.owner

If I do not instantiate Car, but set nissan to None and then call get_owner, I get the following error:

nissan = None
nissan.get_owner()
AttributeError. 'NoneType' object has no attribute 'get_owner'

Is it possible to return None when calling nissan.get_owner() if nissan is None?

The bigger picture: I am writing a Django templatetag that returns some data based on whether database relationships exist. It would be nice to write such code one one line though. In the end, I just want to get the value from get_owner() or get None.

nissan.get_owner() or None

Is not working here...

Upvotes: 1

Views: 2199

Answers (4)

NotSoShabby
NotSoShabby

Reputation: 3708

If Nissan is None, it has no method named "get_owner", meaning you can not call this method on a nissan object (or any method for that case). you need to make nissan a car, and then decide in which circumstances will the get_owner method return none, and implement that in your code

Upvotes: 0

Konstantin Sekeresh
Konstantin Sekeresh

Reputation: 138

getattr() should help you.

 getattr(nissan, 'owner', None)

Also, you don't need get_owner() method -- python way is to access the property directly. Find about property() to get a direction.

Cheers!

Upvotes: 1

Óscar López
Óscar López

Reputation: 236004

Short answer: no, you should not be able to call methods on None objects, I believe you're misunderstanding how object creation works. If you just want to return a None value, then don't assign it in the first place. The correct way to declare an unitialized attribute would be:

class Car(object):
    def __init__(self):
        self.owner = None

And to use it:

nissan = Car()
nissan.owner
=> None
nissan.owner = 'Some Guy'
nissan.owner
=> 'Some Guy'

Also note that get methods are frowned upon in Python, just access the attribute directly.

Now for the big picture - after having clarified how object creation works, you could test whether the object is not null before using it:

nissan.owner if nissan is not None else None

Upvotes: 1

The Pjot
The Pjot

Reputation: 1859

Looking at your bigger picture directly, normal python logic operators can help you with this, the and stops at the first False. So this works just fine:

nissan and nissan.get_owner() or None

Upvotes: 0

Related Questions