Class Relationships
- Aggregation
- Inheritance
Aggregation (Has-A relationship)
Example 1
Explanation
- Creates two classes
CustomerandAddressto model customer data with nested address information
Powered by GPT-4o-mini
Explore how inheritance and aggregation create dynamic class relationships in Python, modeling customer data with nested address details.
Explanation
Customer and Address to model customer data with nested address informationHow was this tutorial?
Customer class stores name, gender, and an Address object, while Address stores city, pin, and state detailsprint_address() in Customer class that prints address components from the embedded address objectAddress object with city 'Vizag', pin '531173', and state 'Andhra Pradesh'print_address() method which outputs the address details: Vizag 531173 Andhra PradeshOutput
Explanation
Customer and Address to model customer data with aggregation relationshipAddress class has private attribute __city and public pin and state attributesCustomer class stores name, gender, and an Address object, with method to print address detailscust.print_address() is called, it accesses the Address object's private __city attribute directlyOutput
Explanation
Customer and Address to model customer data with encapsulated address informationAddress class uses private attribute __city with a getter method get_city() to access it safelyCustomer class stores a reference to an Address object and has a method to print address detailscust.print_address() is called, it outputs the city, pin code, and state from the embedded address objectCustomer contains an Address instance, and proper encapsulation through private attributesOutput
Explanation
Customer and Address to model customer data with encapsulated address informationAddress class stores city, pin, and state with private city attribute and methods to access/edit itCustomer class holds customer details and has methods to print address and edit profile informationedit_profile is called, it updates customer name and calls edit_address on the associated address objectOutput
-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).
Explanation
User with a constructor setting name to 'madhu' and a login method that prints 'login'Student that inherits from User but has its own constructor setting rollno to 100 and an enroll method that prints 'enroll into the course'__init__ method, so it doesn't inherit the name attribute, which leads to an AttributeError when trying to access s.names.name will raise an AttributeError because the Student class doesn't initialize the name attribute from the parent classs.login() work because inheritance allows access to parent methods, but s.enroll() works because it's defined in the child classOutput
Explanation
User with a constructor setting name to 'madhu' and a login method that prints 'login'Student that inherits from User, gaining access to all parent attributes and methodsUser object and one Student objectOutput
Explanation
Output
Explanation
Phone class with a constructor that initializes price, brand, and camera attributes, plus prints a message when calledSmartPhone class that inherits from Phone but has its own constructor that only initializes os and ram attributesSmartPhone constructor doesn't call the parent constructor using super(), so the Phone.__init__ method never executesSmartPhone instance, only "Inside SmartPhone constructor" gets printed, not "Inside phone constructor"s.brand raises an AttributeError because the parent constructor was never called, so the brand attribute was never createdOutput
Explanation
Phone class with a private attribute __price and a public show method that prints the priceSmartPhone class inherits from Phone and tries to access the private __price attribute in its check method using name mangling (_Phone__price)show method in the parent class successfully prints the private price value using print (self.__price)self.__priceOutput
Explanation
brand attribute from the object ss is an instance of a class with a brand attributeOutput
Explanation
s to verify its structure and data types.check() method which is likely part of a schema validation library like Great Expectations or similarOutput
Explanation
Phone class with a private __price attribute and a private method __show that prints the priceSmartPhone class inherits from Phone but tries to access the private __price attribute directly and through name mangling__init__ method prints a message when a Phone object is created and sets up the private __price attributes.show() is called, it will raise an AttributeError because show() is not defined in either class, though __show exists__price becomes _Phone__price internally, but direct access still fails due to inheritance limitationsOutput
Explanation
__num and getter method get_num()Child(Parent)num=100 and calls get_num() to retrieve the private attribute valueshow() method on the Child object which prints "This is in child class"100 followed by "This is in child class" printed to consoleOutput
Explanation
__num and getter method get_num(), then a Child class inheriting from Parent but with its own private attribute __val and getter method get_val()super().__init__(), so Parent's __num remains uninitializedson.get_num() it will raise an AttributeError because __num was never set in the Child instanceson.get_num() since the parent's __num attribute was never initializedOutput
Explanation
__num and getter method get_num__val and getter method get_val__val, not calling parent constructor with super()son.get_val() which returns 100, but son.get_num() would raise AttributeError since Parent's __num was never initializedget_val() method works, not the Parent's methods due to incomplete inheritance setupOutput
Explanation
Output
Explanation
Output
Explanation
Output
Explanation
buy method in both a parent Phone class and a child SmartPhone classSmartPhone class inherits from Phone and overrides the buy method to provide its own implementationSmartPhone instance with SmartPhone(20000, "Apple", 13), it calls the parent's __init__ method first, then stores the price, brand, and camera attributesbuy() method call on the SmartPhone instance executes the overridden version in the child class, printing "Buying a smartphone"Output
Explanation
Phone with a constructor that initializes price, brand, and camera attributes, plus a buy method that prints "Buying a phone"SmartPhone that inherits from Phone and overrides the buy method to print "Buying a smartphone" before calling the parent's buy method using super().buy()__price attribute is private (dunder prefix) while brand and camera are public instance variablesSmartPhone object with price 20000, brand "Apple", and camera 13, it triggers the parent constructor which prints "Inside phone constructor"s.buy() outputs "Buying a smartphone" followed by "Buying a phone" due to the method override and super() callOutput
Explanation
Phone with an __init__ constructor and buy method, plus a child class SmartPhone that inherits from Phone and overrides the buy methodSmartPhone class tries to call super().buy() but this will cause an error because super() can only be used inside the class hierarchy, not from outside__init__ method initializes private price attribute, brand, and camera attributes of the phoneSmartPhone instance, it calls the parent's __init__ method which prints "Inside phone constructor"super() must be called within the child class methods to access parent class functionality, not from external codeOutput
Explanation
Phone class with an initializer that sets price, brand, and camera attributes, and a buy method that prints a message.SmartPhone class that inherits from Phone, overrides the buy method to print a different message, and accesses the parent class's brand attribute using super().SmartPhone with specific values for price, brand, and camera.buy method on the SmartPhone instance, which prints "Buying a smartphone" followed by the brand "Apple".Output
Explanation
Phone class with an initializer that sets price, brand, and camera attributes, printing a message when called.SmartPhone class that inherits from Phone, with its own initializer that adds operating system and RAM attributes, also printing a message.super() to call the parent class's initializer, ensuring the Phone attributes are set when creating a SmartPhone instance.SmartPhone with specific values for price, brand, camera, operating system, and RAM.SmartPhone instance, which outputs "Android" and "Samsung" respectively.Output
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
Explanation
Parent class with a private attribute __num and a method get_num() to access it.Child class that inherits from Parent, adds a private attribute __val, and has a method get_val() to access it.Child named son with num set to 100 and val set to 200.get_num() on son, which returns 100, and get_val(), which returns 200.Output
Explanation
Parent class with an __init__ method that initializes an attribute num to 100.Child class that inherits from Parent, calls the parent's __init__ method using super(), and initializes its own attribute var to 200.show method in the Child class that prints the values of num and var.Child named son and calls its show method.Output
Explanation
Parent class with a private attribute __num initialized to 100 and a method show() that prints its value.Child class that inherits from Parent, initializes its own private attribute __var to 10, and overrides the show() method to call the parent's show() and print its own attribute.Child and calls its show() method, which prints both the parent's and child's private attributes.super() allows the child class to access methods from the parent class.Output
Explanation
Parent class with a private attribute __num initialized to 100 and a method show that prints its value.Child class that inherits from Parent, initializes its own private attribute __var to 10, and overrides the show method to print __var.Child and calls its show method.show method in Child is called, which accesses its own private attribute.Output
Explanation
Phone with an initializer that sets price, brand, and camera attributes, and a method buy that prints a message.SmartPhone class inherits from Phone but does not add any new functionality or attributes.SmartPhone is created with specific values for price, brand, and camera, triggering the Phone constructor and printing "Inside phone constructor".buy method is called on the SmartPhone instance, resulting in the output "Buying a phone".Output
Explanation
Product as the base class, Phone as a derived class, and SmartPhone as a subclass of Phone.Phone class has an __init__ method that initializes price, brand, and camera attributes, and prints a message when an instance is created.buy method in the Phone class prints a message indicating a phone purchase.SmartPhone class inherits from Phone but does not add any new functionality.SmartPhone is created and methods buy and review are called, it outputs messages indicating the purchase and a customer review.Output
Explanation
Phone with an initializer that sets price, brand, and camera attributes, and prints a message when an instance is created.buy method in the Phone class that prints "Buying a phone" when called.Phone, creating two subclasses: SmartPhone and FeaturePhone, which do not add any new functionality.SmartPhone with specific attributes and calls its buy method, resulting in the output "Buying a phone".FeaturePhone with different attributes and also calls its buy method, producing the same output.Output
Explanation
Phone class with an initializer that sets price, brand, and camera attributes, and a method to simulate buying a phone.Product class with a method for customer reviews.SmartPhone class that inherits from both Phone and Product.SmartPhone object with specific attributes and calls its buy and review methods.Output
Explanation
Output
Explanation
Output
Explanation
Output
Explanation
SmartPhone class uses multiple inheritance with Phone and Product as parent classes, showing how Python resolves method calls through the Method Resolution Order (MRO)s.buy(), Python follows the MRO and executes the buy method from the first parent class listed (Product) rather than the Phone class, even though both have a buy method__init__ method of Phone gets called during object creation, printing "Inside phone constructor" and setting up instance variables like __price, brand, and cameraProduct appears first in the inheritance list class SmartPhone(Phone,Product): making it the priority in method resolution orderOutput
Explanation
Output
Explanation
Output
Explanation
Output
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.
Explanation
Output
Explanation
area methods in the Shape class with different parametersarea method with parameters (l, b) overwrites the first one with parameter (radius), so only the second method is actually usables.area(5), it will cause an error because the method expects two arguments but only receives ones.area(5, 6), it correctly calculates and returns the rectangle area (30)Output
Explanation
Output
Explanation
Output
Explanation
Output
Explanation
+ operator.[1, 2, 3] and the second list is [4, 5].[1, 2, 3, 4, 5].Output