python - Assign init arguments automatically in decorator -


i trying assign arguments passed init class. cannot arguments, nor class self (the self init gets passed first arg):

class unpack_arguments(object):      def __init__(self, f):         self.f = f      def __call__(self, *args, **kwargs):         import ipdb; ipdb.set_trace()    class someobject(object):      @unpack_arguments     def __init__(self, one=1, two=2, three=3, four=4):         pass   # @ point, can # # obj = someobject() # obj.one # 1 # obj.two # 2 # obj.three # 3 # obj.four # 4   obj = someobject() 

i try find things can't find class instance of someobject or key names one, two, etc:

ipdb> kwargs {} ipdb> args self = <__main__.unpack_arguments object @ 0x1077a3f60> args = () kwargs = {} ipdb> self.f <function someobject.__init__ @ 0x1077a06a8> ipdb> dir(self.f) ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] ipdb> self.f.__defaults__ (1, 2, 3, 4) ipdb> self.f.__kwdefaults__ ipdb> self.f.__kwdefaults__ ipdb>  

pythonic way use **kwargs:

class someobject(object):     def __init__(self, **kwargs):         name, value in kwargs.items():             setattr(self, name, value)   obj = someobject(a=1, b=2, c=3)  print(obj.__dict__) 

as may see representation of object is:

{'a': 1, 'b': 2, 'c': 3} 

as need base class: here "dummy" implementation:

class someobject_with_init(object):     def __init__(self, **kwargs):         name, value in kwargs.items():             setattr(self, name, value)      def my_name_is(self):         return (self.__class__)   class someobject1(someobject_with_init):     pass   class someobject2(someobject_with_init):     pass   obj = someobject1(a=1, b=2)  obj2 = someobject2(test='1', test2='2')  print(obj.__dict__, obj.my_name_is()) print(obj2.__dict__, obj2.my_name_is()) 

output here be:

{'a': 1, 'b': 2} <class '__main__.someobject1'> {'test': '1', 'test2': '2'} <class '__main__.someobject2'> 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -