简体   繁体   English

在类中的函数调用中将“self”作为参数传递

[英]Passing in "self" as a parameter in function call in a class

I defined a class and within that class, created some methods.我定义了一个类,并在该类中创建了一些方法。 In one of the methods I wish to call another method.在其中一种方法中,我希望调用另一种方法。 What is the reason that I cannot call the method by placing "self" into the argument?我无法通过将“self”放入参数来调用方法的原因是什么? For example, method2(self).例如,method2(self)。

The self parameter is automatically passed in as the object you are calling the method from. self参数作为您调用方法的对象自动传入。 So if I said self.method2() , it automatically figures out that it is calling self.method2(self)所以如果我说self.method2() ,它会自动找出它正在调用self.method2(self)

There are languages that let you write method2() as a shorthand for (what in Python would be) self.method2() , but you can't in Python.有些语言可以让你编写method2()作为(在 Python 中是什么) self.method2()的简写,但你不能在 Python 中。 Python doesn't treat the self argument as special inside the function (except when calling super() ) . Python 不会将self参数视为函数内部的特殊参数(调用super()时除外)

In Python, method2(self) first of all looks up method2 in the current scope.在 Python 中, method2(self)首先在当前作用域中查找method2 It seems like it should be in scope, but it actually isn't because of Python's weird scoping rules.看起来它应该在范围内,但实际上并不是因为 Python 奇怪的范围规则。 Nothing in any class scope is ever visible in nested scopes:在嵌套作用域中,任何class作用域中的任何内容都不可见:

x = 1

class A:
    x = 2

    print(x)  # prints 2

    def method(self):
        print(x)  # prints 1

    class B:
        print(x)  # prints 1

Even if method2 was in scope, calling it directly would call the method from the class currently being defined, not the overridden method appropriate to the dynamic type of self .即使method2在范围内,直接调用它也会从当前定义的类调用该方法,而不是适用于self动态类型的重写方法。 To call that, you must write self.method2() .要调用它,您必须编写self.method2()

You can call a method with self as an argument, but in this case the method should be called as the method of the class, not the instance.您可以使用self作为参数调用方法,但在这种情况下,该方法应作为类的方法而不是实例调用。

class A:
    def method1(self):
        print(1)

    def method2(self):
        A.method1(self)

a = A()
a.method2()
# 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM