Classes-and-object
Classes-and-object
Create a Class
# define a classclass Dog:
sound = "bark" # class attribute
Create Object
An Object is an instance of a Class. It represents a specific implementation
of the class and holds its own data.
Now, let’s create an object from Dog class.
class Dog:
sound = "bark"
# Create an object from the classdog1 = Dog()
# Access the class attributeprint(dog1.sound)
Explanation:
class Dog: Defines a class named Dog.
species: A class attribute shared by all instances of the class.
__init__ method: Initializes the name and age attributes when a new
object is created.
Initiate Object with __init__
class Dog:
species = "Canine" # Class attribute
Self Parameter
self parameter is a reference to the current instance of the class. It allows
us to access the attributes and methods of the object.
class Dog:
def bark(self):
print(self.name)
dog1 = Dog("Buddy", 3)dog1.bark()
__str__ Method
__str__ method in Python allows us to define a custom string representation
of an object. By default, when we print an object or convert it to a string
using str(), Python uses the default implementation, which returns a string
like <__main__.ClassName object at 0x00000123>.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old." # Correct: Returning a
string
dog1 = Dog("Buddy", 3)dog2 = Dog("Charlie", 5)
print(dog1) print(dog2)
Class Variables
These are the variables that are shared across all instances of a class. It is
defined at the class level, outside any methods. All objects of the class share
the same value for a class variable unless explicitly overridden in an object.
Instance Variables
Variables that are unique to each instance (object) of a class. These are
defined within __init__ method or other instance methods. Each object
maintains its own copy of instance variables, independent of other objects.
Example:
class Dog:
# Class variable
species = "Canine"
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows a class (called a child or derived class) to inherit attributes and
methods from another class (called a parent or base class). This promotes
code reuse, modularity, and a hierarchical class structure. In this article, we’ll
explore inheritance in Python.
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
def speak(self):
pass # Placeholder method to be overridden by child classes
# Child class inheriting from Animalclass Dog(Animal):
def speak(self):
return f"{self.name} barks!" # Override the speak method
# Creating an instance of Dogdog = Dog("Buddy")print(dog.speak()) # Output: Buddy
says Woof!
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id
# Driver code
emp = Person("Satyam", 102) # An Object of Person
emp.Display()
def Print(self):
print("Emp class called")
Emp_details = Emp("Mayank", 103)
# calling parent class
Function
Emp_details.Display()
# Calling child class functionEmp_details.Print()
__init__() Function
__init__() function is a constructor method in Python. It initializes the object’s
state when the object is created. If the child class does not define its own
__init__() method, it will automatically inherit the one from the parent class.
In the example above, the __init__() method in the Employee class ensures
that both inherited and new attributes are properly initialized.
# Parent Class: Personclass Person:
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
# Child Class: Employeeclass Employee(Person):
def __init__(self, name, idnumber, salary, post):
super().__init__(name, idnumber) # Calls Person's __init__()
self.salary = salary
self.post = post
Types of Python Inheritance
1. Single Inheritance: A child class inherits from one parent class.
2. Multiple Inheritance: A child class inherits from more than one parent
class.
3. Multilevel Inheritance: A class is derived from a class which is also
derived from another class.
4. Hierarchical Inheritance: Multiple classes inherit from a single parent
class.
5. Hybrid Inheritance: A combination of more than one type of
inheritance.
Example:
Polymorphism in Python
Last Updated : 16 Dec, 2024
Polymorphism is a foundational concept in programming that allows entities
like functions, methods or operators to behave differently based on the type
of data they are handling. Derived from Greek, the term literally means
“many forms”.
Python’s dynamic typing and duck typing make it inherently polymorphic.
Functions, operators and even built-in objects like loops exhibit polymorphic
behavior.
Polymorphism in Functions
Duck typing enables functions to work with any object regardless of its type.
Example:
def add(a, b):
return a + b
print(add(3, 4)) # Integer addition
print(add("Hello, ", "World!")) # String concatenation
Polymorphism in Functions
Duck typing enables functions to work with any object regardless of its type.
Example:
def add(a, b):
return a + b
print(add(3, 4)) # Integer additionprint(add("Hello, ", "World!"))
# String concatenationprint(add([1, 2], [3, 4])) # List concatenation
print(add([1, 2], [3, 4])) # List concatenation