-1

Here is what i am trying to do:

i created a classmethod that returns either an object of dict if not params are added to this method or an object made of list of dicts if any params are added, as code below:

@classmethod
def make_attr(cls, **kwargs):
    """
    code: do something, generate either a tuple 
    """ 
    if :
        data = {}
        """
        add k, v in data
        """
        return cls(**data)
    else:
        data = []
        for k, v in kwargs.items():
            _d = {}
            _d[k] = v
            data.append(_d)
        return cls(*data)


Code as above, and the problem i met is if the classmethod returns object of dict, i can use object.attr to get its value, but if the classmethod returns objects of list, i find no way to unpack it or get its attribute or value, such as:

>> result = Class.make_attr(login_name="test")
>> print("age: ", result.age)
>> age: 25

>> result = Class.make_attr()
>> print(result)
>> <model._class.Class object at 0x104020358>

>> for i in result:
>>     print(i)
>> TypeError: 'Class' object is not iterable

So, how can i make this object iterable?

EUPHORAY
  • 453
  • 6
  • 15

1 Answers1

1

I finally find a way to solve the problem, by adding built-in methods in my class:

class Class:
    def __init__(self, *args, **kwargs):
        self.start = 0
        self.end = args

    def __iter__(self):
        return self

    def __next__(self):
        if self.start >= len(self.end):
            raise StopIteration
        else:
            self.start += 1
            return self.end[self.start-1]

again, thanks @ducminh

EUPHORAY
  • 453
  • 6
  • 15