Passing a parameter to default objects

I want to have a default by default, which includes a parameter when it creates a new object. Is there perhaps a better way to do this?

defaultdict(myobj, param1) 

then myobj:

 class myobj(object): def __init__(self, param1): self.param1 = param1 
+4
source share
1 answer

defaultdict accepts any invoked calls, so you can create a new function that does not accept a parameter, and returns an object created with the desired parameter.

 d = defaultdict(lambda: myobj(param1)) 

Another option is to use functools.partial, which creates a function with one (or more) predefined parameters:

 import functools d = defaultdict(functools.partial(myobj, param1)) 
+5
source

Source: https://habr.com/ru/post/1495398/


All Articles