python 类构造函数
In the last tutorial, we learned how to create a class, its instance and how to access class members(variables and functions). In this tutorial, we will try to improve our understanding about classes by learning more about them. So far, it is known that class
keyword is used to initiate the definition of a class, followed by the name of the class. After finishing the first line with colon we move to next line and starts defining variables or methods after providing proper indentation.
在上一教程中,我们学习了如何创建类,其实例以及如何访问类成员(变量和函数)。 在本教程中,我们将通过学习更多关于类的知识来尝试提高对类的理解。 到目前为止,已知可以使用class
关键字来初始化类的定义,然后使用该类的名称。 用冒号结束第一行后,我们移至下一行,并在提供适当的缩进后开始定义变量或方法。
什么是构造函数? (What is a Constructor?)
As seen in the last tutorial, we know that there are two ways to declare/define a variable of a class.
从上一教程中可以看到,我们知道有两种方法来声明/定义类的变量。
First, by simply defining it inside the class and maybe even initialize it with some value, then and there, pretty much like:
首先,只需在类中定义它,甚至可以使用一些值对其进行初始化,然后到那里,就像:
class Example:
myVariable = "some value";
Second way is to declare them inside any function of the class, using the self
keyword.
第二种方法是使用self
关键字在类的任何函数中声明它们。
Also, it is possible to assign values to the variables while declaring them but sometimes it may happen that the values of these variables may vary for different objects of the same class. In such cases, you'll have to go for assigning values to the variables after the object creation.
同样,可以在声明变量时将其赋值,但有时可能会发生这些变量的值针对同一类的不同