0% found this document useful (0 votes)
14 views

Classes-and-object

The document provides an overview of Python classes and objects, explaining how to create classes, instantiate objects, and use attributes and methods. It covers key concepts such as the __init__() function, class and instance variables, inheritance, and polymorphism. Additionally, it illustrates these concepts with examples, demonstrating how to define and use classes effectively in Python.

Uploaded by

justin cabanero
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Classes-and-object

The document provides an overview of Python classes and objects, explaining how to create classes, instantiate objects, and use attributes and methods. It covers key concepts such as the __init__() function, class and instance variables, inheritance, and polymorphism. Additionally, it illustrates these concepts with examples, demonstrating how to define and use classes effectively in Python.

Uploaded by

justin cabanero
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Classes and Objects

A class in Python is a user-defined template for creating objects. It bundles


data and functions together, making it easier to manage and use them. When
we create a new class, we define a new type of object. We can then create
multiple instances of this object type.
Classes are created using class keyword. Attributes are variables defined
inside the class and represent the properties of the class. Attributes can be
accessed using the dot . operator (e.g., MyClass.my_attribute).

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)

sound attribute is a class attribute. It is shared across all instances of Dog


class, so can be directly accessed through instance dog1.

Using __init__() Function


In Python, class has __init__() function. It automatically initializes object
attributes when an object is created.
class Dog:
species = "Canine" # Class attribute

def __init__(self, name, age):


self.name = name # Instance attribute
self.age = age # Instance attribut

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

def __init__(self, name, age):


self.name = name # Instance attribute
self.age = age # Instance attribute
# Creating an object of the Dog classdog1 = Dog("Buddy", 3)
print(dog1.name) # Output: Buddyprint(dog1.species) # Output: Canine

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 and Instance Variables in Python


In Python, variables defined in a class can be either class variables or
instance variables, and understanding the distinction between them is
crucial for object-oriented programming.

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"

def __init__(self, name, age):


# Instance variables
self.name = name
self.age = age
# Create objectsdog1 = Dog("Buddy", 3)dog2 = Dog("Charlie", 5)
# Access class and instance variablesprint(dog1.species) # (Class
variable)print(dog1.name) # (Instance variable)print(dog2.name) #
(Instance variable)
# Modify instance variablesdog1.name = "Max"print(dog1.name) # (Updated
instance variable)
# Modify class variableDog.species = "Feline"print(dog1.species) # (Updated class
variable)print(dog2.species)

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.

Basic Example of Inheritance

Inheritance allows us to define a class that inherits all the methods and
properties from another class.

# Parent classclass Animal:


def __init__(self, name):
self.name = name # Initialize the name attribute

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!

Creating a Parent Class


In object-oriented programming, a parent class (also known as a base class) defines common
attributes and methods that can be inherited by other classes. These attributes and methods serve
as the foundation for the child classes. By using inheritance, child classes can access and extend
the functionality provided by the parent class.
Here’s an example where Person is the parent class:
# A Python program to demonstrate inheritanceclass Person(object):

# Constructor
def __init__(self, name, id):
self.name = name
self.id = id

# To check if this person is an employee


def Display(self):
print(self.name, self.id)

# Driver code
emp = Person("Satyam", 102) # An Object of Person
emp.Display()

Creating a Child Class


A child class (also known as a subclass) is a class that inherits properties and
methods from its parent class. The child class can also introduce additional
attributes and methods, or even override the ones inherited from the parent.
In this case, Emp is the child class that inherits from the Person class:
class Emp(Person):

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 Built-in Functions


Python’s built-in functions exhibit polymorphism, adapting to various data
types.
Example:

print(len("Hello")) # String length


print(len([1, 2, 3])) # List length
print(max(1, 3, 2)) # Maximum of integers
print(ma x("a", "z", "m")) # Maximum in strings

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

You might also like