0

In the Below code Why can't I use self.f() to refer to secret method which is in A class

def check(f):
    def checking(self):
       print("Before secret method")
       self.f()
       print("After secret method")
    return checking
class A:
    @check
    def secret(self):
        print("Welcome to secret method")
a = A()
a.secret()
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
Santhosh
  • 75
  • 8
  • 3
    because `f` is not an attribute of `A`. `f`, on the other hand , is a variable that refers to the function you decorated, thus `f(self)` will work. – juanpa.arrivillaga Jul 26 '20 at 08:08
  • 2
    [how-does-the-property-decorator-work](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work) - extensive discussion on how decorators work in the accepted answer. – Patrick Artner Jul 26 '20 at 08:13

1 Answers1

0

You are treating "self" as an object of class A by your invocation style, which it isn't. It refers to instance of class A, which is why f(self) works, as the method "secret" requires an instance of class A.

  • U can't have an object itself u will just get a reference which points to object of class A. Then why can't I use self.f() to invoke secret method instead of f(self) – Santhosh Jul 26 '20 at 08:44
  • I think you should look at what instances and objects are in Python. Alternatively you can use simple degugging skills to uncover what that "self" refers to. – Himanshu Jagtap Jul 26 '20 at 08:51