Reputation: 587
I would like to generate a group of classes with same methods but different name
attribute. Eg,
class A:
name = '1'
def f(self):
print('call')
class B
name = '2'
def f(self):
print('call')
class C
name = '3'
def f(self):
print('call')
server.register_handler_class(A)
server.register_handler_class(B)
server.register_handler_class(C)
Values of name
are loaded from xx.conf
file.
How to do this? Do I need metaclass
or __new__
?
Upvotes: 1
Views: 294
Reputation: 39062
IIUC, if you pre-append your variable names by __
, while executing them, the name of the class is automatically appended to the beginning of the respective variables of the classes. So while accessing the variables via Class instance, the variables will become _A__name
, _B__name
and _C__name
. This allows you to use same names without running into problems with conflicting names. You can read my answer here. I am not sure if this is what you meant.
The same can be done for methods as well: __f
Hence you can use
class A:
__name = '1'
def f(self):
print('call')
class B
__name = '2'
def f(self):
print('call')
class C
__name = '3'
def f(self):
print('call')
Upvotes: 0
Reputation: 19885
No, you need type
and globals
:
new_class_names = ['A', 'B', 'C']
def new_class_init(self):
print(f'{self} was called.')
for class_name in new_class_names:
globals()[class_name] = type(class_name, (), {'__init__': new_class_init}
type
can be called with three parameters: name
, bases
and dict
to return a new class.
name
is the name of the new class, bases
a tuple
containing all its base classes and dict
a dict
with key-value pairs representing the method names and actual functions to be bound as methods that the new class should have.
Then, of course, to add them programmatically to the global namespace, we can reference the global dict
by calling globals
.
Upvotes: 2