What is the difference between writing and not writing self in the class method?

Asked 1 years ago, Updated 1 years ago, 109 views

When I made the code in Faicham, they automatically put self on it Why are you doing this?

I wonder what role self plays, so if you take out self, there will be an error.

class Test(object):
  def method_one(self):
    print "Called method_one"

  def method_two(): #The red line here...
    print "Called method_two"

a_test = Test()
a_test.method_one()
a_test.method_two() ##Not allowed

python self bound unbound decorator

2022-09-22 13:13

1 Answers

The side with self attached is called bound, and the side without it is called unbound method.

Usually, when calling a member function, the bound function method_one() is called

a_test.method_one()

Silver

Test.method_one(a_test)

It is converted to . Therefore, TypeError occurs for the unbound function.

>>> a_test = Test() 
>>> a_test.method_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)

If you watch method_two()takes no arguments (1 give) over there, self should be in the role of accepting a_test, but there are too many factors because self is missing.

If you don't want to write self, you can use a decorator to set "This method method_two to not create a bound method."

class Test(object):
    def method_one(self):
        print "Called method_one"

    @staticmethod
    def method_two():
        print "Called method two" #Error gone


2022-09-22 13:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.