Silver
Silver

Reputation: 141

Python creating objects

The essential properties of a Thing are as follows :

  1. The constructor should take in 1 parameter, the name of the Thing.

stone = Thing ('stone ')

  1. 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

  1. 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?

Upvotes: 1

Views: 1331

Answers (3)

sjjhsjjh
sjjhsjjh

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

cco
cco

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

Raphael Parreira
Raphael Parreira

Reputation: 468

  1. When you are writing python code, you need to care about indentation.
  2. Every function within a class needs 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

Related Questions