Classes in Python

Define a class

A Python class can be defined using the class statement.


In [97]:
# Define class
class Car:
    """This is a car class. Described by docstring"""
    def start(self):
        """Define public class method"""
        return('Car has started')

# Create class object
bmw = Car()

# Call public class method
bmw.start()


Out[97]:
'Car has started'

In [98]:
# Retrieve class documentation
help(Car)


Help on class Car in module __main__:

class Car
 |  This is a car class. Described by docstring
 |  
 |  Methods defined here:
 |  
 |  start(self)
 |      Define public class method, bind to containing class using self


In [99]:
# Define class by extending or inheriting a parent class
class WheelCar(Car):
    # Define class variable shared by all instances of this class
    wheels = 4
    
ford = WheelCar()
anotherFord = WheelCar()
ford.wheels, anotherFord.wheels


Out[99]:
(4, 4)

In [100]:
# Define class with an initializer or constructor
class BrandCar(BrandCar):
    # Initialize with instance variable specific to each instance 
    def __init__(self, brand):
        self.brand = brand
    
    def about(self):
        return(self.brand + ' brand car has ' \
               + str(self.wheels) + ' wheels' )

porsche = BrandCar(brand='Porsche')
mustang = BrandCar(brand='Mustang')
porsche.about(), mustang.about()


Out[100]:
('Porsche brand car has 4 wheels', 'Mustang brand car has 4 wheels')

Attribute operations

Using hasattr, setattr, getattr, and del functions you can perform operations on class methods, instance variables, and class variables.


In [101]:
# Methods, class and instance variables are attributes
hasattr(mustang, 'wheels'), hasattr(mustang, 'brand'), \
hasattr(mustang, 'about'), hasattr(mustang, 'start'), \
hasattr(mustang, 'engine')


Out[101]:
(True, True, True, True, False)

In [105]:
# New instance variables can be created by assignment
mustang.engine = 'V8'
hasattr(mustang, 'engine'), hasattr(porsche, 'engine')


Out[105]:
(True, False)

In [102]:
# Set and get attributes
setattr(mustang, 'brand', 'Mustang Plus')
getattr(mustang, 'brand')


Out[102]:
'Mustang Plus'

In [103]:
# Instance variable reference can be deleted
del mustang.brand
hasattr(mustang, 'brand')


Out[103]:
False