Skip to content

Instantly share code, notes, and snippets.

@ojii
Created April 27, 2016 06:07
Show Gist options
  • Select an option

  • Save ojii/cb1a2f1d5d79ed49f552bb8db0b6c7c3 to your computer and use it in GitHub Desktop.

Select an option

Save ojii/cb1a2f1d5d79ed49f552bb8db0b6c7c3 to your computer and use it in GitHub Desktop.
autoinit.py
import inspect
class AutoInit(type):
def __call__(self, *args, **kwargs):
sig = inspect.signature(self.__init__)
data = {
key: parameter.value for key, parameter in sig.parameters.items()
if parameter.default is not parameter.empty
}
params = list(sig.parameters)[1:]
data.update(dict(zip(params, args)))
for key, value in kwargs:
data[key] = value
for key, value in data.items():
setattr(self, key, value)
return super().__call__(*args, **kwargs)
class Foo(metaclass=AutoInit):
def __init__(self, a, b, c): ...
class Bar(metaclass=AutoInit):
def __init__(self, baz):
print(self.baz)
foo = Foo(1, 2, 3)
print(foo.a)
print(foo.b)
print(foo.c)
bar = Bar('hello')
print(bar.baz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment