# We subclass from object to get a class. class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" # Basic initializer def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name # An instance method. All methods take "self" as the first argument def say(self, msg): return "%s: %s" % (self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument @classmethod def get_species(cls): return cls.species # A static method is called without a class or instance reference @staticmethod def grunt(): return "*grunt*"
Creating and Using Objects
# Instantiate a class i = Human(name="Ian") print(i.say("hi")) # prints out "Ian: hi" j = Human("Joel") print(j.say("hello")) #prints out "Joel: hello" # Call our class method i.get_species() #=> "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" i.get_species() #=> "H. neanderthalensis" j.get_species() #=> "H. neanderthalensis" # Call the static method Human.grunt() #=> "*grunt*"
The class Robot below is very similar to the Human class above. Follow these steps on the bottom of the code:
- Create a Robot named "Jim"
- Call the instance method
sayon your robot and pass it the String "Greetings"
- Call the class method
get_specieson your robot.
- Call Robot's static method
Alternatively, you can try out Learneroo before signing up.