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]:
In [98]:
# Retrieve class documentation
help(Car)
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]:
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]:
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]:
In [105]:
# New instance variables can be created by assignment
mustang.engine = 'V8'
hasattr(mustang, 'engine'), hasattr(porsche, 'engine')
Out[105]:
In [102]:
# Set and get attributes
setattr(mustang, 'brand', 'Mustang Plus')
getattr(mustang, 'brand')
Out[102]:
In [103]:
# Instance variable reference can be deleted
del mustang.brand
hasattr(mustang, 'brand')
Out[103]: