Pass a parent class as an argument? - python

Is it possible to leave a parent class unspecified until an instance is created?
e.g. something like this:
class SomeParentClass:
# something
class Child(unspecifiedParentClass):
# something
instance = Child(SomeParentClass)
This obviously does not work. But is it possible to do this somehow?

You can change the class of an instance in the class' __init__() method:
class Child(object):
def __init__(self, baseclass):
self.__class__ = type(self.__class__.__name__,
(baseclass, object),
dict(self.__class__.__dict__))
super(self.__class__, self).__init__()
print 'initializing Child instance'
# continue with Child class' initialization...
class SomeParentClass(object):
def __init__(self):
print 'initializing SomeParentClass instance'
def hello(self):
print 'in SomeParentClass.hello()'
c = Child(SomeParentClass)
c.hello()
Output:
initializing SomeParentClass instance
initializing Child instance
in SomeParentClass.hello()

Have you tried something like this?
class SomeParentClass(object):
# ...
pass
def Child(parent):
class Child(parent):
# ...
pass
return Child()
instance = Child(SomeParentClass)
In Python 2.x, also be sure to include object as the parent class's superclass, to use new-style classes.

You can dynamically change base classes at runtime. Such as:
class SomeParentClass:
# something
class Child():
# something
def change_base_clase(base_class):
return type('Child', (base_class, object), dict(Child.__dict__))()
instance = change_base_clase(SomeParentClass)
For example:
class Base_1:
def hello(self):
print('hello_1')
class Base_2:
def hello(self):
print('hello_2')
class Child:pass
def add_base(base):
return type('Child', (base, object), dict(Child.__dict__))()
# if you want change the Child class, just:
def change_base(base):
global Child
Child = type('Child', (base, object), dict(Child.__dict__))
def main():
c1 = add_base(Base_1)
c2 = add_base(Base_2)
c1.hello()
c2.hello()
main()
Result:
hello_1
hello_2
Works well in both python 2 and 3.
For more information, see the related question How to dynamically change base class of instances at runtime?

Related

Get mangled attribute value of a parent class outside of a class

Imagine a parent class which has a mangled attribute, and a child class:
class Foo:
def __init__(self):
self.__is_init = False
async def init(self):
# Some custom logic here, not important
self.__is_init = True
class Bar(Foo):
...
# Create class instance.
bar = Bar()
# How access `__is_init` of the parent class from the child instance?
How can I get a __is_init value from a parent (Foo) class?
Obviously, I can bar._Foo__is_init in this example, but the problem is that class name is dynamic and I need a general purpose solution that will work with any passed class name.
The solution I see now is iterating over parent classes, and building a mangled attribute name dynamically:
from contextlib import suppress
class MangledAttributeError(Exception):
...
def getattr_mangled(object_: object, name: str) -> str:
for cls_ in getattr(object_, "__mro__", None) or object_.__class__.__mro__:
with suppress(AttributeError):
return getattr(object_, f"_{cls_.__name__}{name}")
raise MangledAttributeError(f"{type(object_).__name__} object has no attribute '{name}'")
Checking that this works:
class Foo:
def __init__(self):
self.__is_init = False
async def init(self):
self.__is_init = True
class Bar(Foo):
def __init__(self):
super().__init__()
bar = Bar()
is_init = getattr_mangled(bar, "__is_init")
print(f"is_init: {is_init}") # Will print `False` which is a correct value in this example
class Foo:
def __init__(self):
self.__is_init = False
async def init(self):
self.__is_init = True
class Bar(Foo):
def getattr_mangled(self, attr:str):
for i in self.__dict__.keys():
if attr in i:
return getattr(self,i)
# return self.__dict__[i] #or like this
bar = Bar()
print(bar.getattr_mangled('__is_init')) #False
if there is a need in __init__ in Bar we should of course initiate Foo's init too by: super().__init__()
When Foo's init is run, self namespace already has attribute name we need in the form we need it (like_PARENT_CLASS_NAME__attrname).
And we can just get it from self namespace without even knowing what parent class name is.

How to override a function in a dict

As part of a message parser I have something similar to what is below, I want to be able to override some of the base class message functions as needed, but the override only works if I add a pass through function. I have lots of these functions and would like to not have to use a pass through function for every message function the child might override.
I know I could provide the functions that the child wants to override as part of the init append operation from the child, but the real messages are a lot more complicated than this simple example and doing that would break the rules I have set for the child classes.
First question is why does it not just work without the pass though, dictionaries are mutable, so the override should be called from the dictionary.
Second question, is there a solution that does not entail the pass though function or appending the override functions to the dictionary from the child init?
class Base():
def set_enable_ind(self):
print("using the pass through hack")
self.set_enable(self)
def set_enable(self):
print("In base class set_enable")
# base msg config dict
msgConfig = {
'setEnable': (set_enable),
}
msgConfigInd = {
'setEnable': (set_enable_ind),
}
def __init__(self, msgConfig=None):
# add the child's messages to the default ones
if msgConfig:
self.msgConfig.update(msgConfig)
self.msgConfigInd.update(msgConfig)
#this one calls the function directly
def msg_recived(self,msg):
self.msgConfig[msg](self)
# this one calls the pass though function
def msg_recived_ind(self,msg):
self.msgConfigInd[msg](self)
class Child(Base):
# override from base class
def set_enable(self, data = None, header=None):
print("In child class set_enable")
# add my own
def disconnect(self, data = None, header=None):
print("In child class disconnect_connection")
# each entry gets a function to call
BtMsgs = {
'disconnect' : (disconnect),
}
def __init__(self):
# call base class __init__ function first, adding my messages
Base.__init__(self, Child.BtMsgs)
if __name__ == "__main__":
child = Child()
#these both work as expected
child.msg_recived('disconnect')
child.msg_recived_ind('disconnect')
#this will always call the Base class function
child.msg_recived('setEnable')
#this will call the child function
child.msg_recived_ind('setEnable')
#output is as follow:
#In child class disconnect_connection
#In child class disconnect_connection
#In base class set_enable
#using the pass through hack
#In child class set_enable
The reason your msg_recived function always calls the Base.set_enable method is because of scoping. When you do:
class Base:
def set_enable(self):
print("In base class set_enable")
msgConfig = {
'setEnable': set_enable, # I removed parens here
}
...
you are telling Python to reference the nearest-scoped set_enable function (the one right above the dictionary).
The reason your Child class never calls its set_enable method, is because you haven't updated the reference in its own msgConfig dictionary. Calling the self.msgConfig.update method is only adding the new key/val reference to the disconnect method of the Child class.
If you change the Child.BtMsgs attribute/dict to have new references, it will work:
class Child(Base):
...
BtMsgs = {
'disconnect': disconnect,
'setEnable': set_enable,
}
def __init__(self):
super().__init__(Child.BtMsgs) # This is Python3.X+ convention
...
Output:
In child class disconnect_connection
In child class disconnect_connection
In child class set_enable
In child class set_enable
This is because 'setEnable': set_enable is now scoped to the one defined inside the Child class.
Regarding my original comment on your question about using __getitem__, getattr, and setattr:
You don't have to subclass dict for these methods to be useful.
class MsgConfig:
def __init__(self, **kwargs):
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def __getitem__(self, item):
return self.__dict__.get(item)
def update(self, d):
if isinstance(d, MsgConfig):
d = d.__dict__
for k,v in d.items():
setattr(self, k, v)
class Base:
def set_enable(self):
print("In base class set_enable")
def __init__(self, msgConfig=None):
self.msgConfig = MsgConfig(setEnable=self.set_enable)
if msgConfig:
self.msgConfig.update(msgConfig)
def msg_recived(self,msg):
self.msgConfig[msg](self)
class Child(Base):
def set_enable(self, data = None, header=None):
print("In child class set_enable")
def disconnect(self, data = None, header=None):
print("In child class disconnect_connection")
def __init__(self):
super().__init__(MsgConfig(disconnect=self.disconnect))
if __name__ == "__main__":
child = Child()
child.msg_recived('disconnect')
child.msg_recived('setEnable')
Output:
In child class disconnect_connection
In child class set_enable
You could try modifying or extending the above class to work for you to automatically pull in necessary message function pointers.

Listing all instance of a class

I wrote a Python module, with several classes that inherit from a single class called MasterBlock.
I want to import this module in a script, create several instances of these classes, and then get a list of all the existing instances of all the childrens of this MasterBlock class. I found some solutions with vars()['Blocks.MasterBlock'].__subclasses__() but as the instances I have are child of child of MasterBlock, it doesn't work.
Here is some example code:
Module:
Class MasterBlock:
def main(self):
pass
Class RandomA(MasterBlock):
def __init__(self):
pass
# inherit the main function
Class AnotherRandom(MasterBlock):
def __init__(self):
pass
# inherit the main function
Script:
import module
a=module.RandomA()
b=module.AnotherRandom()
c=module.AnotherRandom()
# here I need to get list_of_instances=[a,b,c]
Th ultimate goal is to be able to do:
for instance in list_of_instances:
instance.main()
If you add a __new__() method as shown below to your base class which keeps track of all instances created in a class variable, you could make the process more-or-less automatic and not have to remember to call something in the __init__() of each subclass.
class MasterBlock(object):
instances = []
def __new__(cls, *args, **kwargs):
instance = super(MasterBlock, cls).__new__(cls, *args, **kwargs)
instance.instances.append(instance)
return instance
def main(self):
print('in main of', self.__class__.__name__) # for testing purposes
class RandomA(MasterBlock):
def __init__(self):
pass
# inherit the main function
class AnotherRandom(RandomA): # works for sub-subclasses, too
def __init__(self):
pass
# inherit the main function
a=RandomA()
b=AnotherRandom()
c=AnotherRandom()
for instance in MasterBlock.instances:
instance.main()
Output:
in main of RandomA
in main of AnotherRandom
in main of AnotherRandom
What about adding a class variable, that contains all the instances of MasterBlock? You can record them with:
Class MasterBlock(object):
all_instances = [] # All instances of MasterBlock
def __init__(self,…):
…
self.all_instances.append(self) # Not added if an exception is raised before
You get all the instances of MasterBlock with MasterBlock.all_instances (or instance.all_instances).
This works if all base classes call the __init__ of the master class (either implicitly through inheritance or explicitly through the usual super() call).
Here's a way of doing that using a class variable:
class MasterBlock(object):
instances = []
def __init__(self):
self.instances.append(self)
def main(self):
print "I am", self
class RandomA(MasterBlock):
def __init__(self):
super(RandomA, self).__init__()
# other init...
class AnotherRandom(MasterBlock):
def __init__(self):
super(AnotherRandom, self).__init__()
# other init...
a = RandomA()
b = AnotherRandom()
c = AnotherRandom()
# here I need to get list_of_instances=[a,b,c]
for instance in MasterBlock.instances:
instance.main()
(you can make it simpler if you don't need __init__ in the subclasses)
output:
I am <__main__.RandomA object at 0x7faa46683610>
I am <__main__.AnotherRandom object at 0x7faa46683650>
I am <__main__.AnotherRandom object at 0x7faa46683690>

How to change method defaults in Python?

I'm building a class, Child, that inherits from another class, Parent. The Parent class has a loadPage method that the Child will use, except that the Child will need to run its own code near the end of the loadPage function but before the final statements of the function. I need to somehow insert this function into loadPage only for instances of Child, and not Parent. I was thinking of putting a customFunc parameter into loadPage and have it default to None for Parent, but have it default to someFunction for Child.
How do I change the defaults for the loadPage method only for instances of Child? Or am I going about this wrong? I feel like I may be overlooking a better solution.
class Parent():
def __init__(self):
# statement...
# statement...
def loadPage(self, pageTitle, customFunc=None):
# statement...
# statement...
# statement...
if customFunc:
customFunc()
# statement...
# statement...
class Child(Parent):
def __init__(self):
Parent.__init__(self)
self.loadPage.func_defaults = (self.someFunction) #<-- This doesn't work
For such things, I do it in a different way :
class Parent():
def loadPage(self, pageTitle):
# do stuff
self.customFunc()
# do other stuff
def customFunc(self):
pass
class Child(Parent):
def customFunc(self):
# do the child stuff
then, a Child instance would do the stuff in customFunc while the Parent instance would do the "standard" stuff.
Modifying your method as little as possible:
class Parent(object):
def __init__(self):
pass
def loadPage(self, pageTitle, customFunc=None):
print 'pageTitle', pageTitle
if customFunc:
customFunc()
class Child(Parent):
def __init__(self):
Parent.__init__(self)
def loadPage(self, pagetitle, customFunc = None):
customFunc = self.someFunction if customFunc is None else customFunc
super(Child, self).loadPage(pagetitle, customFunc)
def someFunction(self):
print 'someFunction'
p = Parent()
p.loadPage('parent')
c = Child()
c.loadPage('child')
I wouldn't try to do this with defaults. Straightforward class inheritance already provides what you need.
class Parent():
def __init__(self):
# statement...
# statement...
def loadPage(self, pageTitle):
# ... #
self.custom_method()
# ... #
def custom_method(self):
pass # or something suitably abstract
class Child(Parent):
def __init__(self):
Parent.__init__(self)
def custom_method(self):
# what the child should do do
Can the statements before the customFunc() call be exported to a function? and the same for the statements after this call.
If yes, then the parent class will just call these two functions, and the child class will have the customFunc() call between them.
So only the calls will be duplicated.
I may be overlooking a better solution.
Well, the best is probably to rely on an internal attribute, so you would have something like this:
class Parent(object):
def __init__(self):
self._custom_func = None
def load_page(self, page_title):
if self._custom_func:
self._custom_func()
class Child(Parent):
def __init__(self):
super(Parent, self).__init__()
self._load_page = some_function

access calling classes atrributes

I have 2 classes defined as such
class class1():
self.stuff = 1
def blah(self):
foo = class2()
foo.start()
class class2(threading.Thread):
def run(self):
#access class1.stuff
How would I access class1.stuff from class2
It could look like this:
class class1(object):
stuff = 1
def blah(self):
foo = class2()
foo.start()
class class2(threading.Thread):
def run(self):
print(class1.stuff)
There is no special syntax to "access calling classes atrributes". If you want access to a object you must give it a visible name, for example by passing it to __init__ or by using the class object like this.
You would have to pass it into the function.
class class1():
self.stuff = 1
def blah(self):
foo = class2()
foo.start(self)
class class2(threading.Thread):
def run(self, obj):
obj.stuff;
There is no way to access another object's properties without having a reference to the object. The easiest way to obtain a reference to an object of class1 is to ask for it as an argument.

Categories