在 Python 中了解自我

Understanding Self Internally in Python

我完全理解什么在这个例子中传递给了self。我对 如何 它在内部传递给 self 感到很困惑。有人可以帮我理解吗?

class Cars:

    def __init__(self, model, engine, doors):

        self.model = model
        self.engine = engine
        self.doors = doors

tesla = Cars('Model S', 'Electric', 'Four door')
ford = Cars('Mustang', 'v8', 'Two door')

初学者教程没有涵盖很多步骤,所以我会尽量做到简短而透彻。我会尽量准确地使用我的术语,所以您可以查找所有您不清楚的部分。

一般来说,methods in Python are functions in the class object. All functions are descriptors. Part of what being a descriptor means is that when you access a method through the instance of a class, it creates a closure that automatically passes the instance you created it on as the self parameter. For example, if Cars had a method start(self) in addition to __init__, then tesla.start would be a "bound method",这是一个将tesla作为self传递给Cars.start的闭包。请注意,我没有在 tesla.start 之后加上括号。放入括号实际上会调用绑定方法。

第二条信息:如果一个class定义了一个__call__ special method, its instances are said to be callable. This means that you can invoke an instance as if it were a function using the () operator. You can see a case of this when you do tesla = Cars(...). Here Cars is a class object, but you are calling it as if it were a function. We are now getting close to where self actually gets passed in to __init__.

第三,几乎 everything in Python is an object and obeys the general rules you know for objects, like being created from a class, etc. This includes functions and classes. A class object is created from another class, which is appropriately named a metaclass. Normally metaclasses are a can of worms you don't want to open, so we will scratch just enough of the surface here and no more. The most common metaclass is type: 99%1 of all class objects you will encounter as a beginner as instances of type. type defines a __call__ 方法,这就是您在执行 Cars(...) 时调用的方法,因为 Carstype.[=47 的一个实例=]

type.__call__(Cars, ...) 做了一些事情。首先它调用 Cars.__new__(Cars, ...)。这个 returns 您稍后将最终分配给 teslaford 或其他任何东西的新实例。 Then, if the thing that __new__ 返回的是 Cars 的实例,它将调用 Cars.__init__(self, ...),其中 self 是它刚刚创建的新实例。

这就是 self 传递给 __init__ 的方式。请记住,所有步骤都可以 customized 或覆盖,因此这实际上只是对最简单情况的基本概述。


本文中的链接应该可以帮助您开始更具体的研究。所有链接都是完全不同的,即使它们是针对同一个术语的。所有链接都指向 Stack Exchange 站点(所以只有一个例外)或官方 Python 3 文档,只有一个例外。


1这个统计是我编的,但无论如何它可能是对的。