Classes and Objects in Python
Classes and Objects in Python
Objects in Python
Definition:
Key Concepts:
2
What is a Class?
Definition:
Syntax:
class ClassName:
3
What is an Object?
Definition:
Example:
obj = ClassName()
4
Attributes and Methods
Example:
class Dog:
self.name = name
self.age = age
def bark(self):
print("Woof!")
5
The __init__ Method
Example:
class Person:
self.name = name
self.age = age
6
Creating Objects
Example:
p1 = Person("John", 36)
print(p1.age) # Output: 36
7
Inheritance
Definition: A mechanism for creating a new class using details of an existing class.
Example:
class Student(Person):
super().__init__(name, age)
self.student_id = student_id
8
Polymorphism
Definition: The ability to use a common interface for multiple forms (data types).
Example:
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Woof"
9
Encapsulation
Definition: The bundling of data with the methods that operate on that data.
Example:
class Car:
self.__make = make
self.__model = model
def get_make(self):
return self.__make
10
Conclusion
11
References
Sources:
https://www.w3schools.com/
https://www.geeksforgeeks.org/
12