Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:synthetic classes

Tags:

python

class

I can make a synthetic class cls1 that inherits from cls.

>>> class cls(object):
...     def func(self,arg):
...         print 'func',arg
>>> def func1(self):
...     print "func 1 of cls1"
>>> def func2(self):
...     print "func2 of cls1"
>>> d=dict(func1=func1,func2=func2)
>>> cls1=type('cls1',(cls,),d)

Everything works as expected:

>>> obj=cls1()
>>> obj.func(7)
func 7

I can also replace cls1 with FOO:

>>> cls1=type('FOO',(cls,),d)

that gives me:

'cls1': <class '__main__.FOO'>,

Does this (changing __name__ variable) alter the behavior of cls1 and how (everything still works fine)?

like image 812
root Avatar asked Feb 03 '26 01:02

root


1 Answers

You're just changing the name of your class, so it should matter only if you rely on the name somehow:

>>> type(obj)
__main__.FOO
>>> isintance(obj, cls1)
True

That works fine, but what about pickling (that I think rely on the name) ?

For example, before the name change, you can pickle obj without any problem. You can't afterwards.

PicklingError: Can't pickle <class '__main__.FOO'>: it's not found as __main__.FOO
like image 187
Pierre GM Avatar answered Feb 04 '26 13:02

Pierre GM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!