assign None values to all arguments of an arbitrary class'

314 Views Asked by At

I want to make a method whose arguments are an arbitrary class and a list of instances.

let's say the name of the class is 'Price' and the name of the list is 'price_list'

def CreateHTML(_class, _list):
    
   
    one_instance = _class
    list_members = list(one_instance.__dict__)          ##to get the list of member variables' names
    n= len(list_members)

    


CreateHTML(Price(), price_list)    

but the problem is that it works well only if I initially set 'None' values to all arguments of 'Price' class.

class Price:
       def __init__(self, name= None, data = None):
           self.name = name
           self.data = data

is there any ways that the assignment of 'None' values can be automatically handled inside the CreateHTML method??? so that i don't need to initially set Nones to the class. (like below)

class Price:
       def __init__(self, name, data):
             self.name = name
             self.data = data

Thanks!!!

2

There are 2 best solutions below

0
Ankush On

CreateHTML(Price(), price_list) : here Price is expecting 2 items 'name' and 'data'. You have to either pass it while calling the Price('name', 'data') or you have to pass None in your init

2
Karl On

As also noted in my comment above, Price() isn't a class, it is an instance of the class Price. By calling Price() you are essentially instantiating Price with all variables as None. This will only work if Price has default argments such as is set with def __init__(self, name= None, data = None).

If you want a general method with which to instantiate arbitrary classes, you can create something like the following, which takes an arbitrary class and instantiates it will arbitrary arguments (*args) and keyword arguments (**kwargs):

class Price:
   def __init__(self, name, data):
       self.name = name
       self.data = data    

def create_instance(my_class, *args, **kwargs):
    return my_class(*args, **kwargs) 

def CreateHTML(one_instance):
    list_members = list(one_instance.__dict__)          ##to get the list of member variables' names
    n= len(list_members)
    print(f"This instance has {n} members")

  
one_instance1 = create_instance(Price, name="Hello", data="World")
one_instance2 = create_instance(Price, name=None, data=None) 

CreateHTML(one_instance1)
CreateHTML(one_instance2)

You can use create_instance for any class and any arguments, e.g.:

class SomeClass:
   def __init__(self, foo, bar):
       self.foo = foo
       self.bar= bar

one_instance3 = create_instance(SomeClass, "hello", bar="World")

Although to be honest, you don't really gain some much from this. Might as well just use:

one_instance1 = Price(name="Hello", data="World")
one_instance2 = Price(name=None, data=None) 
one_instance3 = SomeClass("hello", bar="World")