Pregunta

I have the following class

class MetricLst(object):
    def __init__(self,n):
        self.min = min(n)
        self.max = max(n)

lst = [1,2,3,4,5]
p = MetricLst(lst)
print p.max
5
print p.min
1

with argument

class MetricArg(object):
    def __init__(self,*args):
        self.min = min(args)
        self.max = max(args)

p = MetricArg(1,2,3,4,5)
p.max
print 5
p.min
print 1

I have the following questions:

  1. if i use MetricArg, is there an elegant way to create the object using a list?
  2. do i need prefer *args when i create a class (if i can)?
¿Fue útil?

Solución

  1. The *args* syntax has a mirror calling equivalent:

    p = MetricArg(*somelist)
    

    The elements of somelist will be used as arguments to MetricArg.

  2. That depends on what kind of API you want to present. If you want to accept 0 or more arguments because that's how you expect your class to be called most conveniently, then you use that form.

    In the Python API, the print() and the os.path.join() functions are well-known examples of callables that use an arbitrary-length parameter list.

Otros consejos

You can pass a list to a variadic function or constructor

L = [1, 2, 3, 4, 5]
p = MetricArg(*L)

Whether or not using a variadic function instead of a function accepting a list it really depends on the function.

Will the function/constructor be called often with a dynamically constructed list or will it receive mostly a fixed number of parameters?

If the list is mostly dynamic then accepting a list is the best idea because you will not clutter the code with *L. On the other hand if in most cases the number of arguments is fixed in the caller and small then just passing the arguments is more readable than building a list just to pass it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top