python and using 'self' in methods
据我所读/理解,"self"参数与"this"类似。
是真的吗?
如果它是可选的,那么如果self没有"传入"方法,您会怎么做?
是的,它也有类似的用途。请注意,它是一个位置参数,您可以随意调用它;但是,有一个强约定可以调用它
Python的快乐
这在某种程度上是正确的。方法绑定到它们所属的对象实例。当你看到
自我的传递有时在你呼叫时是隐含的,例如:
相当于(假设
因为该方法绑定到
您还可以传递方法,并在不从绑定上下文调用时手动传递它们
python文档做得很好:
1 2 3 | xf = x.f while True: print xf() |
will continue to print hello world until the end of time.
What exactly happens when a method is called? You may have noticed that x.f() was called >without an argument above, even though the function definition for f() specified an >argument. What happened to the argument? Surely Python raises an exception when a function >that requires an argument is called without any — even if the argument isn’t actually >used...
Actually, you may have guessed the answer: the special thing about methods is that the >object is passed as the first argument of the function. In our example, the call x.f() is >exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments >is equivalent to calling the corresponding function with an argument list that is created >by inserting the method’s object before the first argument.
它在类方法中不是可选的。如果您试图定义一个没有至少一个参数(即
但是,你可以把它称为
例如方法,实际需要
1 2 3 4 5 | def type_to_display(type): """Converts a pass type to the full written pass type.""" return list((pair[1] for pair in Pass.TYPE_CHOICES if pair[0] == type[0:1].upper()))[0] type_to_display = staticmethod(type_to_display) |
您将永远无法以不传递self的方式使用实例方法。例如,如果我有一个
1 2 3 4 5 6 | class Car: def drive(self): self.do_some_stuff() my_car = Car() my_car.drive() # actually calls Car.drive(my_car) |
EDOCX1 0是指调用该方法的对象,非常类似于C++中的EDCOX1(2)。但重要的是,
在类中,需要一个
1 | SomeObject.some_class_method() |
而一个普通的方法需要你去做
1 2 3 | SomeObject().some_normal_method() or SomeObject.some_normal_method(instance) |