Press ESC to close

Python Class

  • Why Use Classes?

    • Classes help you:

      • ✅ Organize code
      • ✅ Reuse code
      • ✅ Store related data together
      • ✅ Build large applications easily
         
    • Class will have have two things properties & method

     

  • Syntax

class ClassName:
   # Variables
   # Functions (Methods)
  • Creating an Object

class Car:
   pass
   
car1 = Car()
print(car1)

Here:

car1 is an object (instance) of the Car class.

  • Constructor (__init__)

    • The constructor runs automatically when an object is created.
class Car:
   def __init__(self):
       print("Car Created")
car = Car()

Output

Car Created
  • What is self?

    • self refers to the current object.
    • Without self, Python doesn't know which object's data you're referring to.

Example

class Student:
   def __init__(self, name):
       self.name = name
student = Student("Alice")
print(student.name)

Output

Alice
  • Methods

    • Functions inside a class are called methods.
class Student:
   def greet(self):
       print("Hello")
student = Student()
student.greet()

Output

Hello

Example: Variables + Methods

class Student:
   def __init__(self, name):
       self.name = name
   def greet(self):
       print("Hello", self.name)
student = Student("Alice")
student.greet()

Output

Hello Alice

Quick Summary

ConceptMeaning
ClassBlueprint or template
ObjectInstance of a class
__init__()Constructor, called automatically when an object is created
selfRefers to the current object
AttributeVariable inside a class
MethodFunction inside a class

 

 

Related Posts

Python Functions
Python Dict & Tuples
Python Data Types, Lists & For Loop
What is Jupyter Notebook?

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies.