+91 81900 98289

Python Classes/Objects

This Python Classes/Objects lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

class starts the template. Calling the class like a function builds an object. Each object has its own attributes.

Methods are functions defined inside the class. The first parameter is the object itself, by convention named self.

Start here

Two Learner objects do not share a name unless you set one on the class itself.

class Learner: # a template for objects def __init__(self, name): # runs when you create the object self.name = name # store this on the object def label(self): # define the function; it runs when you call it return self.name.upper() # send this value back to the caller print(Learner("Meera").label())

Create and print

Student(\"Asha\") calls __init__ and returns the new object.

class Student: # a template for objects def __init__(self, name): # runs when you create the object self.name = name # store this on the object print(Student("Asha").name)

Add a method

greet reads the name that belongs to that student.

class Student: # a template for objects def __init__(self, name): # runs when you create the object self.name = name # store this on the object def greet(self): # define the function; it runs when you call it return "Hello " + self.name # send this value back to the caller print(Student("Asha").greet())

Change an attribute

Attributes can be updated after the object is created.

class Student: # a template for objects def __init__(self, score): # runs when you create the object self.score = score # store this on the object asha = Student(70) # one object asha.score = 82 # a whole number print(asha.score)
Two Learner objects do not share a name unless you set one on the class itself.