This Python OOP lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
Object-oriented code groups data and the functions that use it. A class is the template. An object is one instance built from that template.
Use a class when several functions keep passing the same bundle of data around. A plain function is enough for a one-step calculation.
Example 1: Start here
The class name is usually Capitalized. The object name is usually lower_case.
class Batch: # a template for objects
def __init__(self, topic): # runs when you create the object
self.topic = topic # store this on the object
python = Batch("Python") # one object
print(python.topic)
Example 2: A tiny class
The class is the template. python is one object built from it.
class Batch: # a template for objects
def __init__(self, topic): # runs when you create the object
self.topic = topic # store this on the object
python = Batch("Python") # one object
print(python.topic)
Example 3: A method uses self
self is the object the method was called on.
class Batch: # a template for objects
def __init__(self, seats): # runs when you create the object
self.seats = seats # store this on the object
def label(self): # define the function; it runs when you call it
return str(self.seats) + " seats" # send this value back to the caller
print(Batch(24).label())
Example 4: Several objects
Each call to Batch creates a separate object.
class Batch: # a template for objects
def __init__(self, topic): # runs when you create the object
self.topic = topic # store this on the object
print(Batch("Python").topic)
print(Batch("SQL").topic)
