The
*args*
syntax has a mirror calling equivalent:p = MetricArg(*somelist)
The elements of
somelist
will be used as arguments toMetricArg
.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 theos.path.join()
functions are well-known examples of callables that use an arbitrary-length parameter list.
Python Can classes take arguments?
-
11-03-2022 - |
Question
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:
- if i use MetricArg, is there an elegant way to create the object using a list?
- do i need prefer *args when i create a class (if i can)?
Solution
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow