0

This is my code:

class bla:
    def function1():
        print 1
    def function2():
        bla.function1()

x = bla()

x.function2()

I don't understand why I get the error "TypeError: function2() takes no arguments (1 given)" as I don't seem to be passing any argument to function2.

4 Answers 4

6

Regular methods are called with an implicit self reference to their object - otherwise they wouldn't be able to access any data members of x.

They should always be declared like so:

class bla:
    def function1(self):
        print 1

if you want them to operate on the object (self is loosely equivalent to the this pointer in C++, for example).

Alternatively, if you don't care about the object (so you're really just using the class to group some functions together), you can make them static like so:

class bla:
    @staticmethod
    def function1():
        print 1

    @staticmethod
    def function2():
        bla.function1()

In fact, that's the only way you can call bla.function1() without an instance of bla from your function2.

Sign up to request clarification or add additional context in comments.

Comments

1

That's cause your calling your function as a method and that automatically binds the method's object as the first argument to your function.

Either do:

bla.function2() #a function call

or:

class bla:
    #normal and correct way to define class methods - first argument is the object on which the method was called
    def function1(self):
        print 1
    def function2(self):
        self.function1()

Comments

0

You have to type:

class bla:
    def function1(self):
        print 1
    def function2(self):
        self.function1()

self (a reference to the object on which the method is called) is passed as the first parameter to each method. The name of this first variable, "self" is just a common convention.

Comments

0

You have to pass the argument self to the functions function1 and function2. See the Python Classes documentation. So your code would be

class Bla: # Notice capitalization. 
    def function1(self):
        print 1
    def function2(self):
        bla.function1()

x = Bla()

x.function2()

See also the answers to the question Why do you need explicitly have the “self” argument into a Python method?.

Basically in Python a call to a member function (like function1)

x = Bla()
x.function1()

is translated into

Bla.function(x)

self is used to refer to the instance of the class x.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.