The essential properties of a Thing are as follows :
- The constructor should take in 1 parameter, the name of the Thing.
stone = Thing ('stone ')
- owner : an attribute that stores the owner object of the Thing, usually a Person object.
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
- is_owned(): returns a boolean value, True if the thing is "owned" and False otherwise.
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?
3 Answers 3
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
Comments
- When you are writing python code, you need to care about indentation.
- Every function within a class needs
selfas 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
2 Comments
self as an argument is just a convention it could be called anything. Instance methods receive the instance as a the first parameter (usually called self), classmethods receive the class as the first parameter (usually called cls) and staticmethods receive nothing.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).
is_ownedbut you have in your codeis_owner. Tell please what exactly is wrong, what output you are getting, and what output you would like to get.