Class and Object-Python
Class and Object-Python
Data Members: These are variables inside the class (e.g., brand, color).
Member Functions (Methods): These are functions defined inside a class that
perform operations (e.g., show_details).
In Python, the default visibility (access control) of class members (attributes and methods) is public.
This means that if you define a variable or method inside a class without any special naming
conventions, it is accessible from outside the class.
Each instance is independent, meaning changing one instance’s attributes does not affect others:
In Python, self is a reference to the instance of the class that is calling the member function. It
allows the function to access and modify instance attributes and call other instance methods.
Each object (s1, s2) has its own separate data because self ensures attributes are stored
per instance.
If we remove self, Python will not know which object's attributes to modify, causing an error.
To fix the error in the incorrect example, we need to add self as the first parameter in the method.
Here’s the corrected version:
In the above code, when object s1 is created using Student(“Alice”), the name Alice is also assigned
to the object using the constructor __init__(). No other function is used here for object’s
initialisation.
Python provides several built-in class attributes that store useful metadata about a class. These
attributes start and end with double underscores (__).
Attribute Description
__bases__ A tuple containing the base classes of the class (used in inheritance).
A destructor is a special method called when an object is deleted or goes out of scope. In Python,
the destructor method is __del__().
Note:
Inheritance in Python
1. Introduction to Inheritance
� Suppose we have a general Animal class, and we want to create a Dog class that inherits
properties of an animal but also has additional behavior.
Explanation
1. Single Inheritance
3. Multilevel Inheritance
A class inherits from another class, which itself inherits from another class.
Hierarchical Inheritance
The child class can override a method from the parent class by defining a new version of it.
Overriding in Python
The method name and parameters must be the same in both the parent and child
classes.
The child class method replaces the parent class method when called from an instance
of the child class.
Data Hiding
In Python, data hiding, a core concept in object-oriented programming (OOP), involves
restricting access to internal data (attributes) of a class, typically by using a double
underscore prefix (__) to denote private members.