简体   繁体   中英

How to use class instance as a json or python dictionary value

Here is the use case.

class EvaluateCustomMethod(object):
    faker = Faker()
    def __init__(self,  custom_method, cardinality=1):
        self.custom_method = custom_method
        self.cardinality = cardinality
    @property  
    def random_first_name(self):
        return self.faker.first.name()

    def call_method_n_times(self):
        return [getattr(self, self.custom_method) \
                for _ in range(self.cardinality)]

f = EvaluateCustomMethod('random_first_name', 1)
f.call_method_n_times()

I am trying to find a way where I do not have to make a method call after instantiating an object and achieve my goal directly when I create an instance.

My ultimate goal is this:

         {"test" : {"name" : EvaluateCustomMethod('random_first_name', 1)}}

This is linked to a previous question

The answer which follows is a don't , since wanting to do what is proposed is very likely to be a strong signal of refactoring need.

One possibility is to use the constructor __new__ , so as to determine what is going to be returned when you instantiate the class. As follows

class EvaluateCustomMethod(object):

    faker = Faker()

    def __new__(cls,  custom_method, cardinality=1):        
        instance = super(EvaluateCustomMethod, cls).__new__(cls)
        instance.custom_method = custom_method
        instance.cardinality = cardinality
        return instance.call_method_n_times()

    @property  
    def random_first_name(self):
        return self.faker.first.name()

    def call_method_n_times(self):
        return [getattr(self, self.custom_method) \
                for _ in range(self.cardinality)]

Which would return

>>> EvaluateCustomMethod('random_first_name', 1)
['John']
>>> {"test" : {"name" : EvaluateCustomMethod('random_first_name', 1)}}
{"test" : {"name" : ['Jack']}}


But actually, overriding __new__ like so is so discouraged, that what you may want to do, more classically, is

 class EvaluateCustomMethod(object): faker = Faker() def __init__(self, custom_method, cardinality=1): self.custom_method = custom_method self.cardinality = cardinality @property def random_first_name(self): return self.faker.first.name() def call_method_n_times(self): return [getattr(self, self.custom_method) \\ for _ in range(self.cardinality)] def __call__(self): return self.call_method_n_times() 

Which returns the same thing, but doing exactly what one thinks it does

 >>> EvaluateCustomMethod('random_first_name', 1) ['Jacques'] >>> {"test" : {"name" : EvaluateCustomMethod('random_first_name', 1)()}} {"test" : {"name" : ['Richard']}} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM