Last Updated: February 25, 2016
·
1.894K
· bt3gl

Python Class & Objects: A Crash Course

Class

We subclass from Python's 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, this is called when this class is instantiated.
    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*"

Testing

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