0

My code:

def inner_function(self):
    x = "one"
    y = "two"

def outer_function(self):
    self.inner_function()
    print "X is %" % x
    print "Y is %" % y

outer_function()

I want the output to be:

>>> X is one
>>> Y is two

I think I'm not understanding the correct use of self in a Python method/function.

The error I'm currently returning is: TypeError: outer_function() takes exactly 1 argument (0 given) Thanks for any help!

1 Answer 1

6

You need:

def inner_function():
    x = "one"
    y = "two"
    return x, y

def outer_function():
    x, y = inner_function()
    print "X is %" % x
    print "Y is %" % y

outer_function()

self is used for instance methods in a class, but here you're just using standalone functions.

Alternatively, for a class:

class MyClass:
    def printme(self):
        print(self.x)

    def mymethod(self):
        self.printme()

a = MyClass()
a.x = "One"
b = MyClass()
b.x = "Two"

a.mymethod()
b.mymethod()

will output:

One
Two

As you can see, you don't need to (and shouldn't) explicitly pass self to a method - Python passes it implicitly. When you call a.mymethod(), self will refer to a, and when you call b.mymethod(), self will refer to b. Without this mechanism, printme(), via mymethod(), would have no way of knowing which object's x to print.

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

2 Comments

thank you. Just so I understand, a method is when a function is associated with a class. Then, to write a method I would need to reference that method's class class which is why I'd put self.method() and def method_name(self): when I construct the methods?
You'd use self.method() to call a method from another method inside that same class. Outside the class you'd make an object and call the method on that, e.g. var = MyClass() followed by var.method(). The point of each method having a self argument is that inside the class itself, you don't know which object it might be called on, so you need a way to refer to whatever the current object is, and that's what self is a reference to. Standalone functions aren't associated with objects, so self would be out of place.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.