Learn Python programming from scratch with our free, beginner-friendly tutorials. Access open-source content, download PDF lessons, and start coding today!
class MyClass:
__init__
Method (Constructor)
def __init__(self, ...)
self
Keyword (Explain early—it’s everywhere!)
self
? (Reference to the instance).obj = MyClass()
.__init__
is called automatically.self.name = name
).class_var = 0
).def greet(self): print("Hello!")
.def set_age(self, age):
.def __init__(self, name="Anonymous")
).Dog
class with name
, breed
, bark()
.Car
class with make
, model
, year
, and describe()
.Student
class with name
, age
, grade
simpleBankAccount
class with balance
, deposit()
, and withdraw()
.Student
class with name
, age
, grade
, and methods like introduce()
.Car
class defines properties like color
, model
, and actions like drive()
.Toyota
car (object) created from the Car
class.class ClassName:
# Attributes & methods go here
MyClass
, BankAccount
).__init__
Method (Constructor)def __init__(self, param1, param2):
self.attribute1 = param1
self.attribute2 = param2
class Dog:
def __init__(self, name):
self.name = name # Initialize 'name' attribute
self
Keywordself
?self
, Python wouldn’t know which object’s attributes to modify.class Dog:
def __init__(self, name):
self.name = name # 'self.name' belongs to this Dog object
object_name = ClassName(arguments)
my_dog = Dog("Buddy") # Calls __init__ automatically
__init__
constructor method, using the self
parameter.class Dog:
def __init__(self, name):
self.name = name # Instance attribute
__init__
.
class Dog:
species = "Canine" # Class attribute (shared)
| Feature | Class Attribute | Instance Attribute |
|————–|—————-|——————-|
| Scope | Shared by all objects | Unique per object |
| Defined | Outside __init__
| Inside __init__
|
self
as the first parameter.class Dog:
def bark(self):
print("Woof!")
my_dog = Dog()
my_dog.bark() # Output: "Woof!"
class Dog:
def set_age(self, age):
self.age = age
my_dog = Dog()
my_dog.set_age(3) # Sets age to 3
class Dog:
def __init__(self, name="Unknown"):
self.name = name
dog1 = Dog() # name = "Unknown"
dog2 = Dog("Buddy") # name = "Buddy"
Dog
Classclass Dog:
species = "Canine" # Class attribute
def __init__(self, name, breed):
self.name = name # Instance attribute
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
# Create objects
dog1 = Dog("Buddy", "Labrador")
dog2 = Dog("Max", "Beagle")
dog1.bark() # Output: "Buddy says Woof!"
Car
Classclass Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def describe(self):
print(f"{self.year} {self.make} {self.model}")
my_car = Car("Toyota", "Corolla", 2020)
my_car.describe() # Output: 2020 Toyota Corolla
Student
Class# Class Definition
class Student:
# Constructor
def __init__(self, name, age, grade): # self refers to the current object being created.
self.name = name
self.age = age
self.grade = grade
# Method
def info(self):
print(f"Name = {self.name} Age = {self.age} Grade = {self.grade}")
# Object Creation
student1 = Student("Hamza", 8, 3)
student2 = Student("Muhammad", 15, 10)
# Accessing Attributes and Methods
print(student1.name)
student1.info()
student2.info()
BankAccount
Classclass BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient funds!")
# Usage
account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
print(account.balance) # Output: 120
Student
ClassRepresents a student with their name, age, and grade.
class Student:
def __init__(self, name, age, grade):
"""Initializes a Student object with the given attributes."""
self.name = name
self.age = age
self.grade = grade
def get_name(self):
"""Returns the student's name."""
return self.name
def get_age(self):
"""Returns the student's age."""
return self.age
def get_grade(self):
"""Returns the student's grade."""
return self.grade
def set_grade(self, new_grade):
"""Updates the student's grade."""
self.grade = new_grade
def introduce(self):
"""Prints a self-introduction message."""
print("Hello, my name is", self.name, "and I'm in grade", self.grade)
# Example usage
student1 = Student("Hamza", 8, 3)
student2 = Student("Muhammad", 16, 10)
student1.introduce() # Output: Hello, my name is Alice and I'm in grade 9
print(student2.get_name()) # Output: Bob
student2.set_grade(11)
print(student2.get_grade()) # Output: 11
Python Tutorial in Urdu: How to Create a Class
Python Tutorial: Python Classes - What is Class Constructor
Python Tutorial in Urdu: How to Create Classes and Instance Attributes