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.

同样,可以在声明变量时将其赋值,但有时可能会发生这些变量的值针对同一类的不同对象而变化的情况。 在这种情况下,您必须在创建对象后为变量分配值。

Again, this can be done in two ways. First, by calling each variable direct from the object, using the dot . symbol, like:

同样,这可以通过两种方式完成。 首先,使用dot直接从对象调用每个变量. 符号,例如:

>>> myObject.myVariable = "some other value";

or we can also ask user for an input:

或者我们也可以要求用户输入:

>>> myObject.myVariable = input();

Besides this we can also assign/modify values of our variables inside class functions using the self keyword.

除此之外,我们还可以使用self关键字在类函数中分配/修改变量的值。

class Example:def anotherFunction(self, parameter1):self.myVariable = parameter1;# or by calling for a user inputself.myVariable = input();

If we have such a function defined in our class, then the object's variables can be initialized or re-initialised by calling the anotherFunction() method and passing the desired value as parameter to this method/function.

如果我们在类中定义了这样的函数,则可以通过调用anotherFunction()方法并将所需的值作为参数传递给该方法/函数来初始化或重新初始化对象的变量。

>>> myObject = Example()
>>> myObject.anotherFunction("Amazing Spiderman")
>>> print (myObject.myVariable)

Amazing Spiderman

神奇蜘蛛侠

As it can be seen, this was a usual user-defined function inside Example class which is utilising parameters to initialize the variable. The concept is fairly simple here. Although, there exists something better, which uses pretty much the same principle and is a defined standard. It's known as a Constructor.

可以看出,这是Example类中通常使用的用户定义函数,它利用参数来初始化变量。 这里的概念非常简单。 虽然,存在更好的东西,它使用几乎相同的原理并且是已定义的标准。 它被称为构造函数

Constructor is a special type of function that is called automatically whenever an object of that class is created. For example,

构造函数是一种特殊的函数类型,每当创建该类的对象时,该函数便会自动调用。 例如,

>>> myObject = Example();

By writing Example() in the code above, we are informing python that myObject is an object of class Example. And that is exactly when the constructor of that class is called.

通过在上面的代码中编写Example() ,我们通知python myObjectExample类的对象。 正是在该类的构造函数被调用时。

But what will it do? Well, generally, the constructors are used to initialize the variables of the class for an object(instance), although it can perform some other tasks as well, like checking if there are enough resources, if the value used to initialize any variable is valid or not, etc.

但是它将做什么? 好吧,通常,构造函数用于初始化一个对象(实例)的类的变量,尽管它也可以执行其他一些任务,例如检查是否有足够的资源,用于初始化任何变量的值是否有效。是否,等等。

在类中定义构造方法 (Defining Constructor method in a class)

In python, the object creation part is divided into two parts:

在python中,对象创建部分分为两部分:

  1. Object Creation

    对象创建

  2. Object Initialisation

    对象初始化

对象创建 (Object Creation)

Object creation is controlled by a static class method with the name __new__. Hence when you call Example(), to create an object of the class Example, then the __new__ method of this class is called. Python defines this function for every class by default, although you can always do that explicitly too, to play around with object creation.

对象的创建由名称为__new__static类方法控制。 因此,当您调用Example()来创建Example类的对象时,将调用该类的__new__方法。 Python默认情况下为每个类都定义了此函数,尽管您也可以始终明确地执行此操作,以进行对象创建。

class Example:def __new__(self):return 'studytonight';# creating object of the class Example
mutantObj = Example()# but this will return that our object
# is of type str
print (type(mutantObj))

In the example above, we have used the __new__ function to change the tyoe of object returned, just to show you what we can do using this function.

在上面的示例中,我们使用了__new__函数来更改返回对象的类型,只是向您展示了我们可以使用该函数做什么。

To see how the default __new__ function works, run the code below, and you will see that this time the object created is of the type Example

若要查看默认的__new__函数如何工作,请运行以下代码,您将看到这次创建的对象属于Example类型

class Example:myVariable = "some value";simpleObj = Example()
print (type(simpleObj))

对象初始化 (Object Initialisation)

Object initialisation is controlled by an instance method with the name __init__ and which is also generally called as a Constructor. Although, both __new__ and __init__ together forms a constructor.

对象初始化由一个名为__init__实例方法控制,该实例方法通常也称为构造函数 。 虽然__new____init__共同构成一个构造函数。

Once the object is created, you can make sure that every variable in the object is correctly initialised by defining an __init__ method in your class, which pretty much means init-iate.

创建对象后,可以通过在类中定义__init__方法来确保正确初始化了对象中的每个变量,这几乎意味着init-iate

Thus, it doesn't matter what the class name is, if you want to write a constructor(to initialise your object) for that class, it has to be the __init__() method. Within this function, you're free to declare a class variable(using self) or initialize them. Here is a quick example for our Example class with __init__ method:

因此,类名是什么都没有关系,如果您想为该类编写一个构造函数(以初始化您的对象),则必须使用__init__()方法。 在此函数中,您可以自由声明类变量(使用self )或对其进行初始化。 这是一个使用__init__方法的Example类的快速示例:

class Example:def __init__(self, value1, value2):self.myVariable1 = value1;self.myVariable2 = value2;print ("All variable initialized")

Once you define the __init__ method in a class, then while creating an object, when you call Example(), you can provide all the necessary parameters required for the object's variables, because when we call Example(), behind the scene python calls the __init__ function for the created object automatically.

一旦在类中定义了__init__方法,然后在创建对象时,调用Example() ,就可以提供对象变量所需的所有必要参数,因为当我们调用Example() ,python在后台调用了__init__函数自动创建的对象。

This is how the code will look:

代码如下所示:

>>> myObj = Example("first variable", "second variable")

You can use this function in lots of ways for initialization. One is already mentioned above using a parameter, another way could be asking user for input inside the constructor.

您可以通过多种方式使用此函数进行初始化。 上面已经提到了使用参数的一种方法,另一种方法是要求用户在构造函数中进行输入。

def __init__(self):self.myVariable1 = input();self.myVariable2 = input();

Below we have a diagram which summarises it all.

在下面,我们有一个图表,总结了这一切。

翻译自: https://www.studytonight.com/python/constructors-in-python

python 类构造函数

python 类构造函数_Python构造函数创建类对象相关推荐

  1. Python基础笔记_Day12_Python元类、type动态创建类、Python动态创建方法、Python运算符、Python发邮件、短信

    Day12_Python元类.type动态创建类.Python动态创建方法.Python运算符重载.Python发邮件.短信 12.01_Python语言基础(类对象)(熟悉) 12.02_Pytho ...

  2. python process 函数_Python Process创建进程的2种方法详解

    前面介绍了使用 os.fork() 函数实现多进程编程,该方法最明显的缺陷就是不适用于 Windows 系统.本节将介绍一种支持 Python 在 Windows 平台上创建新进程的方法. Pytho ...

  3. python在子类中添加新的属性_python - 如何创建类属性?

    python - 如何创建类属性? 在python中,我可以使用@classmethod装饰器向类添加方法. 是否有类似的装饰器向类中添加属性? 我可以更好地展示我在说什么. class Exampl ...

  4. python对象和类区别_python面向对象(类与对象)

    面向对象思想 关注公众号"轻松学编程"了解更多. 1.面向对象的设计思想 面向对象是基于万物皆对象这个哲学观点. 2.面向对象和面向过程的区别 面向过程 在生活中: 它是一种看待问 ...

  5. python中的构造函数_python构造函数init实例方法解析

    这篇文章主要介绍了python构造函数init实例方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.创建对象,我们需要定义构造函数__in ...

  6. python构造函数_Python构造函数

    构造函数是一种特殊类型的方法(函数),它在类的实例化对象时被调用. 构造函数通常用于初始化(赋值)给实例变量. 构造函数还验证有足够的资源来使对象执行任何启动任务. 创建一个构造函数 构造函数是以双下 ...

  7. python init构造函数_python构造函数init实例方法解析

    这篇文章主要介绍了python构造函数init实例方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.创建对象,我们需要定义构造函数__in ...

  8. python新式类和经典类区别_Python中新式类和经典类的区别,钻石继承

    1)首先,写法不一样: class A: pass class B(object): 2)在多继承中,新式类采用广度优先搜索,而旧式类是采用深度优先搜索. 3)新式类更符合OOP编程思想,统一了pyt ...

  9. python编程语言继承_Python面向对象程序设计类的封装与继承用法示例

    本文实例讲述了Python面向对象程序设计类的封装与继承用法.分享给大家供大家参考,具体如下: 访问限制(封装) 1.概念 面向对象语言的三大特征:封装, 继承, 多态. 广义的封装: 类和函数的定义 ...

最新文章

  1. Blender从头到尾创建低多边形角色学习教程 Low Poly Characters – Blender Bitesize Course
  2. Spring注解创建Bean的几种方式
  3. 常用的HTML标签和属性解释
  4. 全面讲解Python列表数组(二),列表分区/片,列表操作符,比较操作符,逻辑操作符,连接操作符,重复操作符,成员关系操作符;
  5. you *might* want to use the less safe log_bin_trust_function_creators variable
  6. 在Vmware下linux与ARM开发板的NFS系统搭建【ZT】
  7. java 三目运算符语法_Java 算术运算及其优先级讲解,可以说很详细了
  8. MATLAB 自带RS编码函数中 gf 数据转化为 double 数组的方法
  9. 淘宝类目批量查询工具v1.0 发布
  10. Dolby与DTS杜比环绕与DTS环绕音响
  11. html编写一个飞机游戏,利用HTML5 Canvas如何制作一个简单的打飞机游戏
  12. IP、 TCP、 UDP协议
  13. 06年及以前韩国星际职业联赛及选手资料
  14. 动态规划-最少硬币组合问题(Java)
  15. H3C路由器交换机模拟器
  16. 租用独立服务器哪个网站好,什么网站适合租用独立服务器
  17. 红灯须硬闯,马路要横穿(文/王路)
  18. 性能调优攻略:完整地讲述了一些代码级别的技术和方法
  19. 以前的记录(加密与解密)
  20. 护士护理报告PPT模板

热门文章

  1. OpenMV图像处理的方法4
  2. Lombok通过@Data注解生成get/set方法时,不生成某个字段的get/set方法
  3. 计算机专业贵州排名2015,2015贵州省大学最佳专业排行榜,贵州大学雄居榜首
  4. vue-cli搭建项目
  5. Java写一个等腰三角形(数字符号都可)
  6. Java设计模式:策略模式
  7. 莫队(离线处理区间询问)
  8. lua协程 unity_XLua 之 Lua 协程 与 Unity 协程互通
  9. JDBC原理实现详解
  10. SQL注入检测模块开源项目DRUID-SQL-WALL学习小结