Is it possible to have alternative inheritance in python3? - python-3.x

My goal:
class BaseClass1:
def f(self)
class BaseClass2:
def f(self)
class DerivedClass:
def g(self):
self.f() # this is either BaseClass1::f() or BaseClass2::f(), depending on instantiation
Where DerivedClass is can be instanced either:
class DerivedClass(BaseClass1)
or
class DerivedClass(BaseClass2)
I understand that this can solve the problem itself:
class UtilityClass1:
def f(self)
class UtilityClass2:
def f(self)
class DerivedClass:
def __init__(self, utilityInstance):
self.utility = utilityInstance
def g(self):
self.utility.f()
d = DerivedClass(UtilityClass1())
d = DerivedClass(UtilityClass2())
However, I specifically want to know, if there is another way, through inheritance (probably using some decorators, or whatever).
Just to wrap things up:
INPUT:
3 class definitions:
class BaseClass1
class BaseClass2
class DerivedClass
OUTPUT:
2 "merged" class instances:
d1 = DerivedClass(BaseClass1)
d2 = DerivedClass(BaseClass2)

Related

Python dynamic inheritance

I wonder if I can somehow do this scenario. I have a Core class that will inherit from some dynamic class, and then pass it and inherits it. maybe with __init__().super(), not sure. can someone help?
file1:
class Core(T):
# some logic
...
file2:
class CustomClass(Core(Logic1)):
def execute():
return self.apply() condition else []
file3:
class CustomClass(Core(Logic2)):
def execute():
return self.apply()
I didn't fully understand your purpose, but I suggest you try to use generics with composition:
from typing import TypeVar, Generic,
T = TypeVar('T')
class Core(Generic[T]):
logic: T
def __init__(self, logic: T, ...):
self.logic = logic
...
class CustomClass(Core[Logic1]):
def __init__(self):
super().__init__(Logic1(...))
def execute():
return self.apply()
....

maximum recursion depth exceeded: abstract property inheritance in python

I am trying to define an abstract class with an abstract property that can then be inherited in a concrete class. But it is giving me maximum recursion depth exceeded.
Vechile is an abstract class and Car implements that class. The base class has a property called parking_ticket which I am keeping out of the __init__ of the abstract class and defining a property called parking_ticket to act as a getter and setter. Please help me to point out where is the mistake.
Abstract Class
"""
module string
"""
from abc import ABC, abstractmethod
from vehicle_type import VehicleType
from parking_ticket import ParkingTicket
class Vechile(ABC):
"""
class docstring
"""
#abstractmethod
def __init__(self, license_plate: str,
kind_of_vehicle: VehicleType) -> None:
self.plate_number = license_plate
self.vehicle_type = kind_of_vehicle
self.parking_ticket = None
#property
#abstractmethod
def parking_ticket(self):
pass
#parking_ticket.setter
#abstractmethod
def parking_ticket(self, parking_ticket: ParkingTicket):
pass
Concrete Class
from vehicle import Vechile
from vehicle_type import VehicleType
from parking_ticket import ParkingTicket
from datetime import datetime, timedelta
class Car(Vechile):
def __init__(self,
license_plate: str) -> None:
super().__init__(license_plate, VehicleType.CAR)
#property
def parking_ticket(self):
return self.parking_ticket
#parking_ticket.setter
def parking_ticket(self,
ticket: ParkingTicket):
self.parking_ticket = ticket
p_ticket = ParkingTicket(ticket_number="123",
plate_number="12345",
allocated_spot_id=10,
issued_at=datetime.utcnow(),
vaccated_at=datetime.utcnow() + timedelta(hours=5),
charges=50
)
c = Car('MH53TS7618')
c.parking_ticket = p_ticket
print(c)
found the answer for it. I was using the same variable name as the method name and instance variable. hence the run time exception was occuring.

Instantiate parent class only once when calling from two child classes

I would like to know if there's a way that we can instantiate a class only once when called from one of the child class and somehow cache it and use it for second child class without instantiating the parent class.
class A:
def __init__(self):
#some huge data stored in self parameters.
class B:
def __init__(self):
A.__init__(self)
class C:
def __init__(self):
A.__init(self)
So both classes B and C uses class A as a parent class and class A has huge data initialised which can be used by both classes B and C. So what I'm trying to achieve here is when I instantiate class B for example, it instantiates class A and loads all the data into memory and to cache the instance so when I immediately instantiate class C it looks for the existing instance of the class without instantiating it again.
How about instantiating A in B and providing a method to transfer the data from B to outside? See below:
class A:
def __init__(self):
self.huge_data = [.....]
def data(self):
return self.huge_data
class B:
def __init__(self):
self.a = A()
def pass_data(self)
return a.data()
class C:
def __init__(self):
A.__init(self)
Once you instantiate B, you will be able to use the method to access the data.

In python multiple inheritance without creating object for a class i'm able to get class variable

class A:
print('class A')
def __init__(self):
print('---1')
print('1')
class B:
print('class B')
def __init__(self):
print('sss')
class C(A,B):
print('222')
def __init__(self):
return 11
class D(B,A):
print('pp')
d1 = D()
I'm getting output:
class A
class B
222
pp
sss
Why 222 is getting print without creating an object for Class C.
Remove d1 = D() and you'll see that the first three lines are still printed.
This is because unlike function definitions, class definitions are not deferred until the class is constructed. The interpreter instead executes each line as it parses it.

Inherit private attribute from abstract class python3

I have an abstract class that i will use as template to implement different kind of subclasses.
I want to define some attributes/methods that are mandatory to all subclasses. For example
class BlockModel(ABC):
def __init__(self, position):
self.__position = position
self.__lives = None
self.__hitbox = None
#property
def lives(self):
return self.__lives
#lives.setter
def lives(self, lives):
self.__lives = lives
#property
def hitbox(self):
return self.__hitbox
#hitbox.setter
def hitbox(self, hitbox):
self.__hitbox = hitbox
#abstractmethod
def method1(self)
#some abstract methods
#abstractmethod
def method2(self)
#some abstract methods
When i create a subclass, for example
class Block1(BlockModel):
def __init__(self,position_):
super().__init__(position_)
self.__lives=1
self.__hitbox = pygame.Rect(self.__position['x'],
self.__position['y'],
5,
5)
#Implement abstract methods
The second class doesn't inherit the attributes __position, __lives, __hitbox, but the public ones without the underscores (i know that there are no real private attributes/methods in python). There s a way too keep them private(with underscores) in the subclass too?

Resources