Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 how to add class instance attributes from list
#1
hi everyone,
My questions is follows
lets say i have
class BaseClass:
    def __init__(self, atr_1=None, atr_2=None, atr_3=None):
        pass
I want to create class instance by passing attributes in the list.

Here is the tricky part, my list of attributes let say has less items..
a_list = ["att_1_data", "att_2_data", "att_4_data"]
1. how i can pass this list of attributes without iterating over list items
2. how can i skip the att_3_data (leave default as None as you see att_3_data is missing from list) and continue to next attr_4_data
I guess somehow i need to use keyword argument..
hope I was able to describe the problem
THANKS
Quote
#2
I see at least two ways. The first way is to create a filtering function that prepares the arguments to be passed to the constructor. You will end up with a syntax such as
instance = BaseClass(**eggs(a_list))
The second way is to create a factory function to create instances with a syntax such as
instance = bacon(a_list)
In your case you could implement these strategies with eg
def eggs(a_list):
    return {'attr_1': a_list[0], 'attr_2': a_list[1]}

def bacon(a_list):
    return BaseClass(attr_1=a_list[0], attr_2=a_list[1])
Quote
#3
(Jul-22-2019, 07:39 AM)Gribouillis Wrote:
instance = BaseClass(**eggs(a_list))
Thanks a lot for quick reply, can you elaborate how **eggs works?
also does it means that my BaseClass need to be created like BaseClass(**kwargs)?

I am sorry i cannot figure it out how the second option works..
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Python complains that class instance is not defined colt 3 199 Sep-17-2019, 12:32 AM
Last Post: ichabod801
  Appending a list in a class from a callback function snizbatch 5 217 Sep-01-2019, 06:27 AM
Last Post: snizbatch
  How do I sum instance attributes? pythonprogrammer 9 478 Jul-18-2019, 07:13 AM
Last Post: perfringo
  Build class to make a Smart list - trying icm63 7 417 Mar-28-2019, 08:53 PM
Last Post: icm63
  Trying to set an instance variable to current value of a class variable ScottDiesing 3 411 Feb-15-2019, 03:12 PM
Last Post: ScottDiesing
  why my method doesn't find my List in the same class? Scorpio 2 336 Jan-31-2019, 05:21 PM
Last Post: Scorpio
  instance of a class in different files DionisiO 2 345 Jan-21-2019, 09:38 PM
Last Post: DionisiO
  Generate list in class P13N 7 801 Dec-28-2018, 10:08 PM
Last Post: P13N
  Printing class instance P13N 2 451 Dec-23-2018, 10:28 PM
Last Post: P13N
  How I can create reference to member of the class instance? AlekseyPython 8 607 Dec-05-2018, 06:24 AM
Last Post: AlekseyPython

Forum Jump:


Users browsing this thread: 1 Guest(s)