Python Class Examples: Init and SelfUse the class keyword. Call the init method to initialize a class.
Class. Writing a small Python program is fairly easy. But composing a large program with many features is more difficult. Classes can help here.
Class usage. With classes, we can divide up the features of the program and only change parts at a time. This helps keep the program easy to maintain.
Init example. This program creates a class. It uses the class keyword and provides two methods. The __init__ method is special. It is a constructor.
Note Init receives parameters and assigns fields to the new class instance. It can validate arguments, do computations, call methods.
Box In the expression Box(10, 2), we create a new instance of the Box class. Its width is set to 10. And its height is set to 2.
Area The area() method will return 20. This is based on the values stored in memory, set by init.
Python program that uses class
return self.width * self.height
def __init__(self, width, height):
self.width = width
self.height = height
# Create an instance of Box.
x = Box(10, 2)
# Print area.
Inheritance. A class can inherit from one or more other classes. The class we want to derive from must be defined. The derived class is specified in the parentheses after the class name.
Here Class B derives from class A. In the statements after the classes, we call size (from class B) and width (from class A).
Size This def method is found directly on class B. It does not exist on class A.
Width This is found by checking the base class of class B, which is class A. Width is a method on class A.
Warning Circular class inheritance is not possible. If B and A both derive from each other, we will get a NameError.
Python program that uses class inheritance
print("a, width called")
print("b, size called")
# Create new class instance.
b = B()
# Call method on B.
# Call method from base class.
b.width()b, size called
a, width called
Two underscores. In a class, some members have two underscores at the start of their names. These are special. The Python language treats them as private.
And Private members can be accessed outside the class, but we must add _ClassName to the start.
Here In class A, we have a field called __value. We must reference this as _A__value outside of the class, but can use __value inside.
Python program that uses two-underscore variable
def __init__(self, value):
self.__value = value
# Two-underscore name.
__value = 0
# Create the class.
a = A(5)
#  Cannot use two-underscore name.
# print(a.__value)#  Must use mangled name.
Issubclass. This determines if one class is derived from another. With this built-in method, we pass two class names (not instances).
Return If the first class inherits from the second, issubclass returns true. Otherwise it returns false.
Tip This is rarely useful to know: a class is considered a subclass of itself. The third issubclass call shows this.
Python program that uses issubclass
print("A says hello")
print("B says hello")
# Use the derived class.
b = B()
# See if B inherits from A.
if issubclass(B, A):
# See if A inherits from B.
if issubclass(A, B):
# Not reached.
# See if A inherits from itself.
if issubclass(A, A):
B says hello
Isinstance. When the first argument (a variable) is an instance of the second argument (a class), isinstance returns true. It will also return true if the class is a base class.
Here For some variables, like lists, the class name may not be specified in the program. But we can still test for "list" this way.
Python program that uses isinstance
# Not called.
# This is an instance of A.
a = A()
if isinstance(a, A):
# This is an instance of the list class.
b = [1, 2, 3]
if isinstance(b, A):
# Not reached.
if isinstance(b, list):
Repr. This accesses the __repr__ method from a class. Repr stands for "representation." It converts an object into a string representation. Here we display Snake instances in a special way.
Tip We return a string from the repr method. The print method automatically calls an object's __repr__ method.
And We can call repr to force the __repr__ method to be used. This lets us store the representation string in a variable.
Python program that uses repr
def __init__(self, type):
self.type = type
return "Snake, type = " + self.type
# Create Snake instance.
# ... Print its repr.
s = Snake("Anaconda")
# Get repr of Snake.
value = repr(s)
print(value)Snake, type = Anaconda
Snake, type = Anaconda
Property. A property gets and sets a value. It is just like a method, but uses simpler syntax. A property can be assigned like a variable. This causes the setter method to be executed.
Here We pass two arguments to the property built-in. We specify getname as the getter, and setname as the setter.
Tip Any code statements can be used in getters and setters. Here we capitalize the string passed to setname.
Snake We create a Snake class instance. Then we assign the "name" property. This invokes the setname method of the Snake class.
Finally We print the value of the name property. This invokes the getname method.
Python program that uses property
def setname(self, value):
# When property is set, capitalize it.
self._name = value.capitalize()
name = property(getname, setname)
# Create a snake instance.
s = Snake()
# Set name property.
s.name = "rattle"
# Get name property.
Super. With the super() built-in, we can get the parent of a class. This gets the immediate ancestor. Here we call super() within the Circle class, which references its parent class, Shape.
Print The name method from Circle prints "Circle." Then name() from Shape is also called.
Python program that uses super
# Call name method from parent class.super().name()
# Create Circle and call name.
c = Circle()
Hash. When comparing objects, a hash code can be used for more speed. A dictionary uses hashes. With __hash__ we implement custom hash computations. A unique value is a good hash.
Here In this program two Snake objects, with the same names and colors, are created. The unique_id is used to compute the hash.
Python program that uses hash on class
def __init__(self, name, color, unique_id):
self.name = name
self.color = color
self.unique_id = unique_id
# Hash on a unique value of the class.
# Hash now is equal to the unique ID values used.
p = Snake("Python", "green", 55)
p = Snake("Python", "green", 105)
Id method. Every object has an id. This is unique to the instance. Its exact number is an implementation detail and will vary between program executions. Here we look at class ids.
Note Ids may be reused when objects are removed by the garbage collector and are not in use. They are rarely useful in code.
Python program that uses id
def __init__(self, color):
self.color = color
cat1 = Cat("black")
cat2 = Cat("orange")
# Each object has a unique id.
# ... The ids may vary between runs.
Classmethod, staticmethod. Python supports special method types (like static methods). These are class methods and static methods.
Type. Built-in methods can create and modify types with statements. The type built-in can replace the "class" declaration. With setattr and getattr we add or load fields.