Classes


Collapse Content

Class Code


# 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*"

Challenge

The class Robot below is very similar to the Human class above. Follow these steps on the bottom of the code:

  1. Create a Robot named "Jim"
  2. Call the instance method say on your robot and pass it the String "Greetings"
  3. Call the class method get_species on your robot.
  4. Call Robot's static method beep.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us