Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the code as follows:

class foo:

    def __init__(self, foo_list, str1, str2):

        self.foo_list = foo_list

        self.str1 = str1

        self.str2 = str2

    def fun(self, l=None, s1=None, s2=None):

        if l is None:

            l = self.foo_list

        if s1 is None:

            s1 = self.str1

        if s2 is None:

            s2 = self.str2

        result_list = [pow(i, 2) for i in l]

        return result_list, s1[-1], len(s2)

Then I create "some_foo" and call "fun" function:

some_foo = foo([1, 2, 3, 4], "March", "June")

print(f.fun())

The output is:

([1, 4, 9, 16], 'h', 4)

which is the correct, but if I do:

print(f.fun("April"))

I get the below error:

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

Apparently, the python confuses the string argument "April" with a list, how do I fix it?

1 Answer

0 votes
by (36.8k points)

By default, your first argument passed to a function will be assigned to a first parameter. If you want to assign a first argument to a second (or n:th) parameter, you must give it as the keyword argument. See, for example

In [19]: def myfunc(x='X', y=5):

    ...: print(x,y)

    ...:

    ...:

# No arguments -> Using default parameters

In [20]: myfunc()

X 5

# Only one positional argument -> Assigned to the first parameter, which is x

In [21]: myfunc(100)

100 5

# One keyword argument -> Assigned by name to parameter y

In [22]: myfunc(y=100)

X 100

The type of arguments do not matter, but a order you used in a function definition.

Want to be a master in Data Science? Enroll in this Data Science Courses

Browse Categories

...