A class, functions as a template that defines the basic characteristics of a particular object. Here's an example:
class Person(object):
"""A simple class.""" # docstring
species = "Homo Sapiens" # class attribute
def __init__(self, name): # special method
"""This is the initializer. It's a special
method (see below).
"""
self.name = name # instance attribute
def __str__(self): # special method
"""This method is run when Python tries
to cast the object to a string. Return
this string when using print(), etc.
"""
return self.name
def rename(self, renamed): # regular method
"""Reassign and print the name attribute."""
self.name = renamed
print("Now my name is {}".format(self.name))
There are a few things to note when looking at the above example.
__init__()
method is called the initializer. It's equivalent to the constructor in other object oriented languages, and is the method that is first run when you create a new object, or new instance of the class.__init__()
; this is not necessary, but it is recommended (since attributes defined outside of __init__()
run the risk of being accessed before they are defined).self
is used for this parameter (usage of self
is actually by convention, as the word self
has no inherent meaning in Python, but this is one of Python's most respected conventions, and you should always follow it).private
elements, so everything, by default, imitates the behavior of the C++/Java public
keyword. For more information, see the "Private Class Members" example on this page.__functionname__(self, other_stuff)
. All such methods are called "magic methods" and are an important part of classes in Python. For instance, operator overloading in Python is implemented with magic methods. For more information, see the relevant documentation.Now let's make a few instances of our Person
class!
>>> # Instances
>>> kelly = Person("Kelly")
>>> joseph = Person("Joseph")
>>> john_doe = Person("John Doe")
We currently have three Person
objects, kelly
, joseph
, and john_doe
.
We can access the attributes of the class from each instance using the dot operator .
Note again the difference between class and instance attributes:
>>> # Attributes
>>> kelly.species
'Homo Sapiens'
>>> john_doe.species
'Homo Sapiens'
>>> joseph.species
'Homo Sapiens'
>>> kelly.name
'Kelly'
>>> joseph.name
'Joseph'
We can execute the methods of the class using the same dot operator .
:
>>> # Methods
>>> john_doe.__str__()
'John Doe'
>>> print(john_doe)
'John Doe'
>>> john_doe.rename("John")
'Now my name is John'