Python - Objects
In Python, a method is called on an object using dot notation. Dot notation involves using the object's name followed by a dot and then the method's name with parentheses. This syntax indicates that the method should be executed in the context of the specific object.
Calling a Method on an Object:
- Use dot notation:
object_name.method_name()
- Include parentheses even if the method does not take any parameters.
- Methods are associated with a specific class and operate on the data (attributes) of the object.
Let's illustrate how to call a method on an object with a simple Python program:
# Define a class named 'Circle' with a method for calculating the area
class Circle:
def __init__(self, radius):
self.radius = radius
# Method to calculate the area of the circle
def calculate_area(self):
return 3.14 * self.radius**2
# Create an instance (object) of the 'Circle' class
circle_instance = Circle(radius=4)
# Call the method to calculate the area of the circle
area_of_circle = circle_instance.calculate_area()
In this example, we define a class 'Circle' with a method ('calculate_area') that performs an operation on the attribute ('radius') of the object. We then create an instance ('circle_instance') of the 'Circle' class and call the method to calculate the area.
The method is called using dot notation, indicating that it should be executed in the context of the specific instance.
Output:
Area of the circle: 50.24
The key takeaway is that calling a method on an object involves using dot notation to specify the object's name, followed by the method's name with parentheses. This syntax allows objects to execute their own set of behaviors and computations.
In Python, both instance methods and class methods are types of methods associated with a class. However, they serve different purposes and have distinct use cases.
Difference between Instance and Class Methods:
- Instance Method: An instance method is a method that operates on an instance of the class. It takes 'self' as its first parameter, representing the instance on which the method is called.
- Class Method: A class method is a method that operates on the class itself rather than on instances. It takes 'cls' as its first parameter, representing the class on which the method is called.
Let's illustrate the difference between instance and class methods with a simple Python program:
# Define a class named 'Person' with both instance and class methods
class Person:
total_people = 0 # Class attribute shared by all instances
def __init__(self, name):
self.name = name
Person.total_people += 1 # Increment the class attribute on instance creation
# Instance method to get the name of the person
def get_name(self):
return self.name
# Class method to get the total number of people
@classmethod
def get_total_people(cls):
return cls.total_people
# Create instances (objects) of the 'Person' class
person1 = Person(name="Alice")
person2 = Person(name="Bob")
# Call instance methods to get names
name_person1 = person1.get_name()
name_person2 = person2.get_name()
# Call class method to get the total number of people
total_people = Person.get_total_people()
In this example, we define a class 'Person' with an instance method ('get_name') and a class method ('get_total_people'). The instance method operates on individual instances, while the class method operates on the class itself.
We then create instances ('person1' and 'person2') of the 'Person' class and call both instance and class methods.
Output:
Name of person 1: Alice Name of person 2: Bob Total number of people: 2
The key distinction is that instance methods are called on instances and have access to the instance's data, while class methods are called on the class and have access to the class's data.
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or derived class) to inherit attributes and methods from an existing class (base class or superclass). This enables code reuse and the creation of a hierarchy of classes.
Concept of Inheritance and Subclasses:
- Base Class (Superclass): The class whose attributes and methods are inherited by another class.
- Derived Class (Subclass): The class that inherits attributes and methods from another class. It can also have additional attributes and methods.
- Subclassing: The process of creating a new class based on an existing class.
Let's illustrate the concept of inheritance and subclasses with a simple Python program:
# Define a base class named 'Shape' with attributes and a method
class Shape:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
# Define a subclass named 'Circle' that inherits from the 'Shape' class
class Circle(Shape):
def __init__(self, color, radius):
# Call the constructor of the base class using super()
super().__init__(color)
self.radius = radius
# Additional method in the subclass
def calculate_area(self):
return 3.14 * self.radius**2
# Create an instance (object) of the 'Circle' class
circle_instance = Circle(color="red", radius=5)
# Access attributes and call methods from both base and derived classes
color_of_circle = circle_instance.get_color()
area_of_circle = circle_instance.calculate_area() # Available only in the subclass
In this example, we define a base class 'Shape' with an attribute ('color') and a method ('get_color'). We then create a subclass 'Circle' that inherits from the 'Shape' class. The subclass has an additional attribute ('radius') and method ('calculate_area').
We create an instance ('circle_instance') of the 'Circle' class and demonstrate how to access attributes and call methods from both the base and derived classes.
Output:
Color of the circle: red Area of the circle: 78.5
The key takeaway is that inheritance allows the reuse of code, and subclasses can extend or override the functionality of the base class. This concept provides a powerful mechanism for creating hierarchies of related classes in Python.
Method overriding in Python allows a subclass to provide a specific implementation for a method that is already defined in its superclass. This enables the subclass to customize or extend the behavior inherited from the base class.
Overriding Methods in a Subclass:
- Base Class (Superclass): The class that defines a method to be overridden.
- Derived Class (Subclass): The class that overrides a method from the base class.
- Method Signature: The overridden method in the subclass must have the same name and parameters as the method in the base class.
Let's illustrate how to override methods in a subclass with a simple Python program:
# Define a base class named 'Animal' with a method to make a sound
class Animal:
def make_sound(self):
return "Generic animal sound"
# Define a subclass named 'Cat' that overrides the 'make_sound' method
class Cat(Animal):
def make_sound(self):
# Call the overridden method from the base class using super()
base_sound = super().make_sound()
return f"Meow! ({base_sound})"
# Create an instance (object) of the 'Cat' class
cat_instance = Cat()
# Call the overridden method in the subclass
cat_sound = cat_instance.make_sound()
In this example, we define a base class 'Animal' with a method 'make_sound'. We then create a subclass 'Cat' that inherits from 'Animal' and overrides the 'make_sound' method with a specific implementation.
We create an instance ('cat_instance') of the 'Cat' class and call the overridden method to customize the sound.
Output:
Cat sound: Meow! (Generic animal sound)
The key concept is that the overridden method in the subclass has the same name and parameters as the method in the base class. The use of 'super()' allows the subclass to invoke the overridden method from the base class and extend or modify its behavior.