Lesson 1 of 7 · Classes and Objects · 2 min read · Updated
Classes and objects
Designing your own type: a class is the plan, and each object is one thing built from it.
So far your data and the functions that use it have lived apart. A class puts them together. It is a blueprint; each object (or instance) made from it carries its own data and knows what it can do.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def passed(self):
return self.marks >= 50
priya = Student("Priya", 87)
arun = Student("Arun", 42)
print(priya.name, priya.marks)
print(priya.passed(), arun.passed())
arun.marks = 55
print(arun.passed())
Priya 87
True False
True
class Student:defines the new type. Class names use CapitalWords.__init__runs automatically when an object is created, to set it up.selfis the object itself.self.name = namestores a value on that object.- A function inside a class is a method. Python passes the object as
selffor you.
Example
priya.passed() is really Student.passed(priya). That is all self is: the object before the dot, handed to the method as its first argument.
Warning
Forgetting self is the most common class error. Leave it out of def passed(self): and calling it raises TypeError: takes 0 positional arguments but 1 was given — the 1 is the object Python passed in.
class Student:
def __init__(self, name):
self.name = name
meena = Student("Meena")
print(type(meena).__name__)
print(isinstance(meena, Student))
Student
True
What is self inside a method?
Try this now
- Write a
Rectangleclass with width and height, and methodsarea()andperimeter(). - Create three Student objects in a list and print the names of those who passed.
Create a free account to save your progress, or sign in.