Reputation: 141
The essential properties of a Thing are as follows :
stone = Thing ('stone ')
In OOP, we set this attribute to None during initialization when this Thing does not belong to any Person yet (to signify the absence of an object value).
stone . owner
None
stone . is_owned ()
False
4.get_owner(): returns the Person object who owns the Thing object.
stone . get_owner ()
None
Implement the class Thing such that it satisfies the above properties and methods.
im not sure what is wrong with my code:
class Thing:
def __init__(self,name):
self.name=name
self.owner=None
def is_owned(self):
return self.owner!=None
def get_owner(self):
return self.owner
My question: as the question states, when i input stone.owner, i expect to receive an output None. however, there is no output at all. edit: no output received is accepted instead of None. However, is there any way to return None from stone.owner?
Upvotes: 1
Views: 1331
Reputation: 333
Here is an answer using a property with getter.
class Thing(object):
def __init__(self, name):
self.name = name
self.owner = None
@property
def isOwned(self):
return self.owner is not None
thing = Thing('stone')
print("owner:", thing.owner)
print("isOwned:", thing.isOwned)
print("Setting owner.")
thing.owner = "Silver"
print("owner:", thing.owner)
print("isOwned:", thing.isOwned)
Output is like this:
$ python3 ./thingclass.py
owner: None
isOwned: False
Setting owner.
owner: Silver
isOwned: True
Upvotes: 2
Reputation: 6281
The reason nothing is printed is most likely that the Python REPL does not print None
values.
The current code in the question is better than the accepted answer (except for the indentation) because None
is a singular value in Python, while "None"
is an ordinary string (which is neither equal to None
nor treated as a False
value, both of which are true for None
).
Upvotes: 1
Reputation: 468
self
as parameter.So, your code must be:
class Thing:
def __init__(self,name):
self.name=name
self.owner="None"
def is_owned(self):
return self.owner!="None"
def get_owner(self):
return self.owner
Upvotes: 1