I'm confused. How type() takes more than on parameter? And what is the core purpose on this expression?
self.data = [type('', (), dict(output=input))() for input in dnn_input_list]
Somebody help me to understand why code is written like this.
I'm confused. How type() takes more than on parameter? And what is the core purpose on this expression?
self.data = [type('', (), dict(output=input))() for input in dnn_input_list]
Somebody help me to understand why code is written like this.
type
is a class. type
is a metaclass. The instances it creates are classes. In Python, classes are instances of type
. If I do:
A = type("A", (), {}}
That is equivalent to:
class A:
pass
The first argument is the .__name__
of the class, the second argument is a tuple of types to inherit from, and the third argument is the class namespace.
You can think of a class definition statement as synatic sugar for the creation of a class
This code dynamically creates a list of classes. Note, if you do something like:
Foo = type("Foo", (), {"bar": 42})
That is equivalent to:
class Foo:
bar = 42
So, type('', (), dict(output=input))()
creates a type, and the type has a single attribute, output
, with a value provided by the list of inputs, then instantiates that class to create an instance of it. Consider:
>>> Foo = type("Foo", (), {"bar": 42})
>>> foo = Foo()
>>> foo.bar
42
It isn't clear why this code takes this route, since it is unnecessarily creating a class for each of these instances. More typically, you would just want:
class SomeName: # anonymous name
def __init__(self, output):
output = outpout
class MainClass:
def some_method(self):
...
self.data = [SomeName(input) for input in dnn_input_list]
Possibly, this was a over-engineered way of creating something like types.SimpleNamspace
:
>>> import types
>>> obj = types.SimpleNamespace(foo='bar', baz=42)
>>> obj
namespace(foo='bar', baz=42)
>>> obj.foo
'bar'
>>> obj.baz
42
The type() function in Python can be used to create new classes dynamically. It takes three arguments. The first argument is the name of the class. The second argument is a tuple of base classes. The third argument is a dictionary that defines the attributes of the class.
input_value = 10
DynamicClass = type('', (), {'output': input_value})
obj = DynamicClass()
print(obj.output)
# Output: 10