Class Relationships
- Aggregation
- Inheritance
Aggregation (Has-A relationship)
Python class inheritance and object composition with customer address management
Explanation
- Defines a Customer class that accepts a name, gender, and address object as parameters during initialization
- Creates an Address class to store location details including city, pin code, and state information
- Demonstrates object composition by passing an Address instance as a parameter to the Customer constructor
- Shows how to access nested object attributes through method calls to display complete address information
- Illustrates the relationship between parent and child classes through encapsulated data structures
Output
Understanding Class Composition and Private Attributes in Python
Explanation
- The
Customerclass is initialized with a name, gender, and anAddressobject, demonstrating composition. - The
Addressclass contains private and public attributes for city, pin, and state, showcasing encapsulation. - The
print_addressmethod in theCustomerclass attempts to access the private attribute__cityfrom theAddressclass, illustrating the concept of private access modifiers. - An instance of
Addressis created and passed to theCustomerinstance, highlighting how objects can be composed in Python. - The comment at the end emphasizes that private attributes cannot be accessed directly outside their class, reinforcing the importance of encapsulation.
Output
This code defines a Customer class that utilizes an Address class to manage and display customer addresses.
Explanation
- The
Customerclass initializes with a name, gender, and an instance of theAddressclass. - The
print_addressmethod in theCustomerclass retrieves and prints the city, pin, and state from the associatedAddressinstance. - The
Addressclass encapsulates address details, including a private city attribute, which is accessed through theget_citymethod. - An instance of
Addressis created with specific values, and aCustomerinstance is initialized with this address. - Finally, the
print_addressmethod is called to display the customer's address information.
Output
This code defines a Customer class that manages customer profiles and their associated addresses.
Explanation
- The
Customerclass initializes with a name, gender, and anAddressobject, allowing for structured customer data. - The
print_addressmethod retrieves and prints the city, pin, and state from the associatedAddressobject using theget_citymethod. - The
edit_profilemethod allows updating the customer's name and modifying the address details through theedit_addressmethod of theAddressclass. - The
Addressclass encapsulates address details, using private attributes for the city to restrict direct access, promoting data encapsulation. - An instance of
Addressis created and linked to aCustomer, demonstrating how to create and manipulate customer profiles and their addresses.
Output
Aggregation class diagram
Inheritance
- What is inheritance
- Example
- What gets inherited?
Inheritance and it's benefits
-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).
Demonstrating Inheritance and Method Access in Python Classes
Explanation
- Defines a parent class
Userwith an initializer that sets anameattribute and aloginmethod. - Introduces a child class
Studentthat inherits fromUser, allowing access to its attributes and methods. - The
Studentclass has its own initializer that sets arollnoattribute and anenrollmethod. - Instances of both classes are created, showcasing how the
Studentinstance can access the inheritednameattribute and theloginmethod from theUserclass. - The output demonstrates the functionality of both classes by printing the
name,rollno, and invoking theloginandenrollmethods.
Output
Demonstrating inheritance and method access in Python classes
Explanation
- The
Userclass serves as a parent class with a constructor that initializes thenameattribute and aloginmethod. - The
Studentclass inherits from theUserclass, allowing it to access thenameattribute andloginmethod. - An instance of
Useris created asu, while an instance ofStudentis created ass. - The code prints the
nameattribute from theStudentinstance, calls the inheritedloginmethod, and invokes theenrollmethod specific to theStudentclass. - This demonstrates the concept of inheritance, where the child class can utilize properties and methods of the parent class.
Output
Class Diagram (Triangle)
What gets inherited?
- Constructor
- Non Private Attributes
- Non Private Methods
This code defines a Phone class and a SmartPhone subclass to demonstrate object-oriented programming in Python.
Explanation
- The
Phoneclass is initialized with three attributes:price,brand, andcamera, which are set during object creation. - The
__init__method prints a message indicating the constructor is being executed. - The
buymethod in thePhoneclass allows for simulating the purchase of a phone by printing a message. - The
SmartPhoneclass inherits from thePhoneclass, allowing it to use the same properties and methods without redefining them. - An instance of
SmartPhoneis created with specific attributes, and thebuymethod is called to demonstrate functionality.
Output
Understanding Constructor Behavior in Inheritance with Python Classes
Explanation
- The
Phoneclass defines a constructor that initializes three attributes:price,brand, andcamera, while also printing a message when an instance is created. - The
SmartPhoneclass inherits fromPhonebut defines its own constructor that initializesosandram, effectively overriding the parent class's constructor. - When an instance of
SmartPhoneis created, thePhoneconstructor is not executed, demonstrating that the child class's constructor replaces the parent's. - The
s.brandline accesses thebrandattribute from thePhoneclass, but since thePhoneconstructor is not called,brandremains uninitialized unless explicitly set in theSmartPhoneconstructor. - This code snippet illustrates the concept of constructor overriding in Python's class inheritance model.
Output
Understanding Private Member Access in Inheritance with Python Classes
Explanation
- The
Phoneclass has a private attribute__price, which is not directly accessible from child classes. - The
SmartPhoneclass inherits fromPhoneand attempts to access the private attribute using the name mangling technique (_Phone__price). - The
showmethod in thePhoneclass serves as a getter to print the private__priceattribute. - When an instance of
SmartPhoneis created, it can access the private member using the mangled name but cannot access it directly asself.__price. - This demonstrates how Python's name mangling protects private attributes from being accessed directly in subclasses.
Output
Accessing and displaying the brand attribute of an object in Python
Explanation
- The code snippet uses the
print()function to output the value of thebrandattribute from an objects. - It assumes that
sis an instance of a class that has a defined attribute calledbrand. - If the
brandattribute exists, its value will be printed to the console; otherwise, an AttributeError will occur. - This is a common practice in object-oriented programming to retrieve and display object properties.
Output
This code snippet invokes a method to perform a check on an object or system.
Explanation
- The
check()method is called on the objects, which likely performs a validation or diagnostic operation. - The specific functionality of
check()depends on the implementation of the class or module to whichsbelongs. - This method may return a boolean value, raise exceptions, or produce output indicating the status of the check.
- It is commonly used in scenarios where preconditions need to be verified before proceeding with further operations.
Output
Understanding private member access in Python classes with inheritance
Explanation
- The
Phoneclass has a private attribute__price, which cannot be accessed directly outside the class. - The
SmartPhoneclass inherits fromPhone, allowing it to access the private attribute using name mangling (_Phone__price). - The
__showmethod inPhoneis a private method and cannot be called directly from an instance ofSmartPhone. - The constructor of
SmartPhoneinitializes the parent classPhonewith price, brand, and camera parameters. - The code attempts to call
s.show(), which will raise an error sinceshowis not defined inSmartPhoneorPhone.
Output
Demonstrating inheritance and encapsulation in Python classes
Explanation
- The
Parentclass initializes a private attribute__numthrough its constructor, ensuring encapsulation. - The
get_nummethod in theParentclass provides a way to access the private attribute__num. - The
Childclass inherits from theParentclass, allowing it to access theget_nummethod. - The
showmethod in theChildclass prints a message, demonstrating additional functionality in the subclass. - An instance of
Childis created with the value100, and both the inherited methodget_numand theshowmethod are called, showcasing polymorphism.
Output
Demonstrating inheritance and encapsulation in Python classes
Explanation
- The
Parentclass initializes a private attribute__numand provides a methodget_numto access it. - The
Childclass inherits fromParentbut initializes its own private attribute__valwithout calling the parent's initializer, which can lead to an error when accessing__num. - An instance of
Childis created with values100and10, but it will raise an error when trying to accessget_num()since the parent constructor is not invoked. - The
get_valmethod in theChildclass allows access to the private attribute__val. - The
printstatements attempt to display both the parent's and child's values, illustrating the use of encapsulation and method overriding in class design.
Output
Demonstrating inheritance and encapsulation in Python classes
Explanation
- The
Parentclass initializes a private attribute__numand provides a methodget_numto access it. - The
Childclass inherits fromParentbut initializes its own private attribute__valwithout calling the parent's constructor. - The
get_valmethod in theChildclass allows access to the private attribute__val. - An instance of
Childis created with values100and10, but only__valis accessible throughget_val. - The output displays the value of
__valfrom theChildinstance, demonstrating encapsulation.
Output
Demonstrating inheritance and method usage in Python classes
Explanation
- The code defines two classes,
AandB, whereBinherits fromA. - Class
Ahas an initializer that sets an instance variablevar1to 100 and a methoddisplay1that prints this variable. - Class
Bcontains a methoddisplay2that also prints the inheritedvar1from classA. - An object of class
Bis created, and bothdisplay1anddisplay2methods are called, showcasing how inherited properties can be accessed. - The output will show the value of
var1from classA, which remains 100, regardless of the argument passed to the methods.
Output
Demonstrating inheritance and method usage in Python classes
Explanation
- The code defines two classes,
AandB, whereBinherits fromA. - Class
Ahas an initializer that sets an instance variablevar1to 100 and a methoddisplay1that prints its argument. - Class
Bcontains a methoddisplay2that prints its argument, but it does not override any methods from classA. - An instance of class
Bis created, and bothdisplay1anddisplay2methods are called with different arguments, demonstrating method functionality across inherited classes. - The output will show the values passed to each display method, illustrating how inheritance allows access to methods from the parent class.
Output
Understanding inheritance and method overriding in Python classes
Explanation
- The code defines two classes, A and B, where B inherits from A.
- Class A has an initializer that sets an instance variable
var1to 100 and a methoddisplay1that updatesvar1and prints it. - Class B has a method
display2that prints the current value ofvar1inherited from class A. - An object of class B is created, and
display1is called with the argument 200, updatingvar1to 200. - Finally,
display2is called, which prints the updated value ofvar1from class A.
Output
Demonstrating method overriding in Python inheritance with phone and smartphone classes
Explanation
- The code defines a base Phone class with a constructor that initializes price, brand, and camera attributes while printing a constructor message
- The SmartPhone class inherits from Phone and overrides the buy method with its own implementation that prints a different message
- When creating a SmartPhone instance and calling its buy method, the overridden version executes instead of the parent class method due to polymorphism
- This showcases how child classes can modify parent class behavior through method overriding while maintaining the same method signature
- The output demonstrates "Buying a smartphone" rather than "Buying a phone" because the child class explicitly redefines the buy functionality
Output
Super Keyword
This code defines a Phone class and a SmartPhone subclass with overridden methods for purchasing behavior.
Explanation
- The
Phoneclass initializes with attributes for price, brand, and camera, while printing a message during construction. - The
buymethod in thePhoneclass outputs a message indicating a phone purchase. - The
SmartPhoneclass inherits fromPhoneand overrides thebuymethod to provide a specific message for smartphone purchases. - The
super().buy()call within theSmartPhoneclass allows access to the parent class'sbuymethod, ensuring both messages are printed. - An instance of
SmartPhoneis created with specific attributes, and callings.buy()demonstrates the overridden behavior.
Output
Demonstrating the incorrect usage of super() outside a class context in Python
Explanation
- The code defines a base class
Phonewith an initializer that sets price, brand, and camera attributes. - A derived class
SmartPhoneinherits fromPhoneand overrides thebuymethod to provide specific functionality. - An instance of
SmartPhoneis created with specific attributes, but the attempt to callsuper().buy()outside the class context results in an error. - The correct usage of
super()should be within a method of the child class to access methods from the parent class. - This snippet highlights the importance of understanding the scope and context in which
super()can be utilized.
Output
Understanding super() method usage and parent class attribute access in Python inheritance
Explanation
- The code demonstrates inheritance where SmartPhone class extends Phone class and overrides the buy method
- When calling super().brand inside the child class buy method, it attempts to access the brand attribute from the parent class
- However, this will raise an AttributeError because brand is not a method but a public instance variable, and super() can only access methods, not direct attributes
- The code structure shows proper class initialization with private price attribute and public brand/camera attributes
- The output would display "Buying a smartphone" followed by an AttributeError when trying to access super().brand
Output
Understanding Inheritance and Constructor Initialization in Python Classes
Explanation
- The
Phoneclass is defined with an initializer that sets the price, brand, and camera attributes while printing a message indicating the constructor is called. - The
SmartPhoneclass inherits fromPhoneand has its own initializer that adds operating system and RAM attributes. - The
super()function is used to call the parent class's constructor, ensuring that thePhoneattributes are initialized properly. - An instance of
SmartPhoneis created with specific values, demonstrating how attributes from both the parent and child classes are set. - The final two print statements output the operating system and brand of the smartphone instance, showcasing attribute access from the derived class.
Output
Inheritance in summary
-
A class can inherit from another class.
-
Inheritance improves code reuse
-
Constructor, attributes, methods get inherited to the child class
-
The parent has no access to the child class
-
Private properties of parent are not accessible directly in child class
-
Child class can override the attributes or methods. This is called method overriding
-
super() is an inbuilt function which is used to invoke the parent class methods and constructor
Demonstrating inheritance and encapsulation in Python classes
Explanation
- The
Parentclass initializes a private attribute__numand provides a methodget_num()to access its value. - The
Childclass inherits fromParent, calling its constructor withsuper()to initialize__numand adds a private attribute__val. - The
Childclass includes a methodget_val()to return the value of its private attribute__val. - An instance of
Childis created with values100and200, and bothget_num()andget_val()methods are called to print the respective values. - This code illustrates the principles of encapsulation by using private attributes and inheritance to extend functionality.
Output
Demonstrating inheritance and method overriding in Python classes
Explanation
- The
Parentclass initializes an attributenumwith a value of 100. - The
Childclass inherits fromParentand calls the parent's constructor usingsuper(), initializingnumand adding its own attributevarwith a value of 200. - The
showmethod in theChildclass prints both the inheritednumand thevarattributes. - An instance of
Childis created and theshowmethod is called, displaying the values ofnumandvar.
Output
Demonstrating inheritance and private attributes in Python classes
Explanation
- The
Parentclass initializes a private attribute__numwith a value of 100. - The
showmethod in theParentclass prints the value of__num. - The
Childclass inherits fromParentand initializes its own private attribute__varwith a value of 10. - The
showmethod in theChildclass calls theshowmethod of theParentclass to display__num, followed by printing its own__var. - An instance of
Childis created, and callingobj.show()outputs both the parent's and child's private attributes.
Output
Demonstrating inheritance and encapsulation in Python classes
Explanation
- The
Parentclass initializes a private variable__numset to 100 and has a methodshowto print its value. - The
Childclass inherits fromParentand initializes its own private variable__varset to 10, overriding theshowmethod to print__var. - The
super().__init__()call in theChildclass constructor ensures that theParentclass's constructor is executed, initializing__num. - When an instance of
Childis created andshowis called, it prints "Child: 10", demonstrating method overriding. - The private variables
__numand__varcannot be accessed directly outside their respective classes, showcasing encapsulation.
Output
Types of Inheritance
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance(Diamond Problem)
- Hybrid Inheritance
Demonstrating single inheritance in a Python class structure for a phone and smartphone
Explanation
- The
Phoneclass is defined with an initializer that sets the price, brand, and camera specifications. - The
buymethod in thePhoneclass allows for simulating the purchase of a phone. - The
SmartPhoneclass inherits from thePhoneclass, gaining its properties and methods without additional modifications. - An instance of
SmartPhoneis created with specific attributes, and thebuymethod is called to demonstrate functionality.
Output
Demonstrating multilevel inheritance in a product hierarchy with Python classes
Explanation
- The
Productclass serves as a base class with a method to print customer reviews. - The
Phoneclass inherits fromProduct, adding attributes for price, brand, and camera, and includes a method to simulate buying a phone. - The
SmartPhoneclass inherits fromPhone, allowing it to utilize both thebuymethod and the inheritedreviewmethod fromProduct. - An instance of
SmartPhoneis created with specific attributes, and both thebuyandreviewmethods are called to demonstrate functionality.
Output
This code defines a hierarchical class structure for different types of phones in Python.
Explanation
- The
Phoneclass initializes with attributes for price, brand, and camera specifications. - The
buymethod in thePhoneclass allows for simulating the purchase of a phone. SmartPhoneandFeaturePhoneare subclasses ofPhone, inheriting its properties and methods.- Instances of
SmartPhoneandFeaturePhoneare created with specific attributes and invoke thebuymethod to demonstrate functionality. - The use of encapsulation is indicated by the double underscore in
self.__price, suggesting that this attribute is intended to be private.
Output
Python multiple inheritance with constructor chaining and method resolution order
Explanation
- The code demonstrates multiple inheritance where SmartPhone class inherits from both Phone and Product parent classes
- The Phone constructor initializes private price attribute, brand, and camera attributes while printing a constructor message
- When creating SmartPhone instance, the constructor is called only once from the first parent class (Phone) due to Python's Method Resolution Order (MRO)
- The buy() method is inherited from Phone class and executes successfully on the SmartPhone object
- The review() method is inherited from Product class and works correctly through multiple inheritance mechanism
Output
This code demonstrates the creation of a smartphone class that inherits from both phone and product classes.
Explanation
- The
Phoneclass initializes with attributes for price, brand, and camera, and includes a method to simulate buying a phone. - The
Productclass has a method for customer reviews, which takes a rating as an argument. - The
SmartPhoneclass inherits from bothPhoneandProduct, allowing it to utilize methods and properties from both parent classes. - An instance of
SmartPhoneis created with specific attributes, and both thebuyandreviewmethods are called on this instance. - The code illustrates basic principles of inheritance and method usage in Python.
Output
This code defines a smartphone class that inherits features from both phone and product classes.
Explanation
- The
Phoneclass initializes with attributes for price, brand, and camera, and includes a method to simulate buying a phone. - The
Productclass has a method for reviewing a product based on a rating. - The
SmartPhoneclass inherits from bothPhoneandProduct, allowing it to access methods from both parent classes. - An instance of
SmartPhoneis created with specific attributes, and methods from both parent classes are called to demonstrate functionality. - The output showcases the constructor message from
Phone, followed by the buying action and customer review.
Output
This code demonstrates the creation of a smartphone class that inherits properties from both a phone and a product class.
Explanation
- The
Phoneclass initializes with attributes for price, brand, and camera, and includes a method to simulate buying a phone. - The
Productclass contains a method for reviewing a product based on a rating. - The
SmartPhoneclass inherits from bothPhoneandProduct, allowing it to utilize methods and properties from both parent classes. - The constructor of
SmartPhonecalls the parentPhoneconstructor usingsuper(), ensuring proper initialization of inherited attributes. - An instance of
SmartPhoneis created with specific values, and methods from both parent classes are called to demonstrate functionality.
Output
Understanding the diamond problem in Python through class inheritance and method resolution order
Explanation
- The code defines a
Phoneclass with an initializer that sets price, brand, and camera attributes, and includes abuymethod. - A
Productclass is created with its ownbuymethod that prints a different message. - The
SmartPhoneclass inherits from bothPhoneandProduct, demonstrating multiple inheritance. - When an instance of
SmartPhoneis created, thebuymethod from theProductclass is called due to Python's method resolution order (MRO), which prioritizes the first class listed in the inheritance. - The output confirms that the
Product'sbuymethod is executed, illustrating how Python handles the diamond problem by following the MRO.
Output
Understanding method overriding and inheritance in Python classes
Explanation
- The code defines three classes: A, B, and C, where B inherits from A, and C inherits from B.
- Class A has a method
m1that returns the integer 20. - Class B overrides the
m1method to return 30 and introduces a new methodm2that returns 40. - Class C overrides the
m2method to return 20, while it inherits the overriddenm1method from class B. - The final print statement calculates the sum of
m1fromobj1(20),m1fromobj3(30), andm2fromobj3(20), resulting in a total of 70.
Output
Understanding method overriding and super calls in a class hierarchy
Explanation
- The code defines three classes: A, B, and C, where B inherits from A and C inherits from B.
- Class A has a method
m1that returns the integer 20. - Class B overrides the
m1method, calling the parent class'sm1usingsuper()and adding 30 to the result, returning 50. - Class C also overrides the
m1method, but it mistakenly callsself.m1(), which leads to infinite recursion since it keeps calling its ownm1method. - When an object of class C is created and
m1is called, it will result in a RecursionError due to the infinite loop in method calls.
Output
This code demonstrates method overriding and the use of super() in a class hierarchy.
Explanation
- Class A defines a method
m1that returns the integer 20. - Class B inherits from A and overrides the
m1method to add 30 to the result of the superclass'sm1method, resulting in 50. - Class C inherits from B and further overrides the
m1method, adding 20 to the result of B'sm1, yielding a final result of 70. - An instance of class C is created, and calling
m1on this instance returns 70, demonstrating the cumulative effect of method overrides in the inheritance chain.
Output
Polymorphism
- Method Overriding
- Method Overloading
- Operator Overloading
Polymorphism means "many forms". It refers to the ability of an entity (like a function or object) to perform different actions based on the context.
Technically, in Python, polymorphism allows same method, function or operator to behave differently depending on object it is working with. This makes code more flexible and reusable.
Demonstrating method overriding and polymorphism in Python classes
Explanation
- The
Animalclass defines a methodsound()that returns a generic sound. - The
DogandCatclasses inherit fromAnimaland override thesound()method to return specific sounds ("Bark" and "Meow", respectively). - A list named
animalscontains instances ofDog,Cat, andAnimal. - A loop iterates through the
animalslist, calling thesound()method on each instance, showcasing polymorphic behavior where the method called depends on the object's class. - This code illustrates how method overriding allows subclasses to provide specific implementations of methods defined in a parent class.
Output
Understanding Method Overloading Behavior in Python Classes
Explanation
- The
Shapeclass defines two methods namedarea, intended to calculate the area of different shapes based on the parameters provided. - The first
areamethod calculates the area of a circle using the formula πr², while the second calculates the area of a rectangle using the formula length × breadth. - In Python, method overloading does not function as it does in some other languages; the second definition of
areaoverrides the first, meaning only the rectangle calculation is retained. - The output of
print(s.area(5))will result in an error since the firstareamethod is not accessible, whileprint(s.area(5, 6))will correctly return 30. - This behavior highlights the need for alternative approaches, such as using default parameters or variable-length arguments, to achieve similar functionality.
Output
This code defines a Shape class that calculates the area of a circle or rectangle based on provided dimensions.
Explanation
- The
Shapeclass contains a methodareathat calculates the area based on one or two parameters. - If only one argument
ais provided, it calculates the area of a circle using the formula πr² (approximated as 3.14). - If two arguments
aandbare provided, it calculates the area of a rectangle using the formula length × width. - An instance of the
Shapeclass is created, and theareamethod is called twice: once for a circle and once for a rectangle. - The results of the area calculations are printed to the console.
Output
This code snippet demonstrates string concatenation using operator overloading in Python.
Explanation
- The
+operator is used to concatenate two strings,'hello'and'world'. - Python's operator overloading allows the
+operator to be redefined for different data types, such as strings. - The result of this operation is a single string,
'helloworld', which combines both input strings without any separator. - This feature enhances code readability and allows for intuitive operations on user-defined types as well.
Output
This code performs a simple arithmetic addition of two integers.
Explanation
- The code adds the integers 4 and 5 together.
- The result of the addition is 9.
- This operation demonstrates basic arithmetic functionality in Python.
- It can be used as a building block for more complex calculations.
Output
This code snippet demonstrates how to concatenate two lists in Python.
Explanation
- The code uses the
+operator to combine two lists,[1, 2, 3]and[4, 5]. - The result of the operation is a new list that contains all elements from both lists in the order they were added.
- The original lists remain unchanged after the concatenation.
- This method is commonly used for merging lists in Python programming.
Output
Next in this series: Python Abstraction: Master Abstract Classes & Interfaces →

