![]() _getattribute_ can be called on an object to retrieve an attribute by name. _getattr_ can be defined on a class and will be called whenever an attribute is referenced but not defined. The basis for doing this lies with builtin methods _getattr_ and _getattribute_. In response to a comment made by Lev Barenboim, the following demonstrates how you can make composition with delegation appear to be more like regular inheritance so that if class C has has assigned an instance of class A, for example, to self.instance, then attributes of A such as x can be accessed internally as self.x as well as (assuming class C does not define attribute x itself) and likewise if you create an instance of C named c, you can refer to that attribute as c.x as if class C had inherited from class A. # assign an instance of A or B depending on whether argument use_A is True Instead of using inheritance, you can use composition with delegation. Whether you're just starting out with OOP or have been doing it for a while, I would suggest you get a good book on design patterns. The required output would be 'Class A is the parent class, the number is 7' followed by 'Class B is the parent class, no number given'. Print('Class B is the parent class, no number given') Print('Class A is the parent class, the number is 7',self.num) Can anyone suggest a better way to do this? class A: The corresponding class will have to be inherited based on certain conditions at the time of object creation.įor example, I tried to make Class C inherit A or B based on whether any arguments were passed at the time of instantiating, but in vain. The reason I am trying to do this is because I have multiple methods with the same name but in three parent classes which have different functionality. Being new to OOP, I wanted to know if there is any way of inheriting one of multiple classes based on how the child class is called in Python. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |