python 类构造函数_Python构造函数创建类对象

本文介绍了Python中的构造函数,它是创建类对象时自动调用的特殊函数,用于初始化类的变量。构造函数在Python中称为`__init__`,通过它可以设置对象创建后的初始状态。此外,还讨论了对象创建和初始化的两个阶段:对象创建由`__new__`方法控制,对象初始化由`__init__`方法(构造函数)控制。
摘要由CSDN通过智能技术生成

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.

同样,可以在声明变量时将其赋值,但有时可能会发生这些变量的值针对同一类的不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值