Tiancheng Liu
Tiancheng Liu

Reputation: 873

How to convert all elements automatically in a list to a given object in Python

I want to create a list child class that can convert all elements automatically in it to an object no matter the element is create by init or append or extend. So by using both for loop or getitem. Here's a simple example code. What kind of magic method should I use?

class A():
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return 'Object A with name {}'.format(self.name)    

class CustomerList(list):
    def __init__(self, *args):
        super(CustomerList, self).__init__(*args)        

c = CustomerList('a')
c.append('b')
c[0]   # Object A with name a
c[1]   # Object A with name b
for ele in c:
    print(c)
# Object A with name a  
# Object A with name b  

Upvotes: 1

Views: 575

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113998

are you asking how to override __append__?

class A():
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return 'Object A with name {}'.format(self.name)    

class CustomerList(list):
    def __init__(self, *args):
        super(CustomerList, self).__init__(*args)   
    def append(self,letter):
        super(CustomerList, self).append(A(letter))   

I guess???.. but as mentioned in the comments if you want

my_custom_list.extend(["A","B","V"])
my_custom_list[2] = "A"

to work you will need to override

 def __setitem__(self,key,value): # cover a[2]='A'
     super(CustomerList,self).__setitem__(key,A(value))

 def extend(self,other):
     super(CustomerList,self).extend([A(val) for val in other])

of coarse you probably then need to override both __add__,__iadd__ at a minimum as well

Upvotes: 2

TerryA
TerryA

Reputation: 59984

I think what you're trying to do is: When you append a new item into the list, it is an object of class A. What you can do is override list.append function:

class A():
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Object A with name {}'.format(self.name)    

class CustomerList(list):
    def __init__(self, *args):
        super(CustomerList, self).__init__(*args)  
    def append(self, arg):
        new_obj = A(arg)
        self.insert(len(self), new_obj)

Upvotes: 1

Related Questions