Bob liao
Bob liao

Reputation: 701

Why can't bound method access the outside function in a class?

Something really confused me today. Let's assume foo.py :

class A:
    def a(self):
        b()
        #c()

    @staticmethod
    def b():
        print("b called!")


def c():
    print("c called!")

a=A()

a.a()

print(a.a)
print(type(A.b))
print(type(c))

Then when I access function b in a I will encounter error:NameError: name 'b' is not defined. Can't function b be accessed inside method a? Both b and c are functions, only c can be accessed inside a.Why?

Upvotes: 0

Views: 767

Answers (2)

Campbell McDiarmid
Campbell McDiarmid

Reputation: 494

Try calling self.b() instead of b() when referring to the member function b of the class A. Each instance of A is a unique object, members and attributes of an instance can be referred to using self.

class A:
    def a(self):
        self.b()
        c()

    @staticmethod
    def b():
        print("b called!")

def c():
    print("c called!")

We can refer to c without using self.c() as it is not a member of A. Member function b does not take self as the first argument, as a staticmethod does not call to or alter any other members of the object. Member function a is not considered a staticmethod of A, because it calls another member function (b) of the instance self.

(Note: self is not a keyword, but a widely used convention).

Upvotes: 1

Bohdan Shulha
Bohdan Shulha

Reputation: 74

I think it is because of the b is the static method of the class A, not just a function from the outer scope. It has to be accessible with this syntax:

A.b()

Upvotes: 0

Related Questions