当我在Python中实例化类时会发生什么?(What happens when I instantiate class in Python?)

编程入门 行业动态 更新时间:2024-10-28 14:28:00
我在Python中实例化类时会发生什么?(What happens when I instantiate class in Python?)

你能澄清Python类和类实例背后的一些想法吗?

考虑一下:

class A(): name = 'A' a = A() a.name = 'B' # point 1 (instance of class A is used here) print a.name print A.name

打印:

B A

如果相反在point 1我使用类名,输出是不同的:

A.name = 'B' # point 1 (updated, class A itself is used here)

打印:

B B

即使Python中的类是类实例的某种原型,我也希望已经创建的实例保持不变,即输出如下:

A B

你能解释一下究竟发生了什么吗?

Could you clarify some ideas behind Python classes and class instances?

Consider this:

class A(): name = 'A' a = A() a.name = 'B' # point 1 (instance of class A is used here) print a.name print A.name

prints:

B A

if instead in point 1 I use class name, output is different:

A.name = 'B' # point 1 (updated, class A itself is used here)

prints:

B B

Even if classes in Python were some kind of prototype for class instances, I'd expect already created instances to remain intact, i.e. output like this:

A B

Can you explain what is actually going on?

最满意答案

首先,Python中创建实例字段(而不是类字段)的正确方法是使用__init__方法。 我相信你已经知道了。

Python不会限制您为对象的非声明字段赋值。 例如,请考虑以下代码:

class Empty: pass e = Empty() e.f = 5 print e.f # shows 5

那么代码中的内容是:

使用A指定的静态字段name创建A类。 您创建A的实例, a 。 您为对象a创建一个新字段(但不为其他A实例创建)并为其分配B 您打印a.name的值,该值对象a是唯一a 。 您打印属于该类的静态字段A.name的值

First of all, the right way in Python to create fields of an instance (rather than class fields) is using the __init__ method. I trust that you know that already.

Python does not limit you in assigning values to non-declared fields of an object. For example, consider the following code:

class Empty: pass e = Empty() e.f = 5 print e.f # shows 5

So what's going in your code is:

You create the class A with a static field name assigned with A. You create an instance of A, a. You create a new field for the object a (but not for other instances of A) and assign B to it You print the value of a.name, which is unique to the object a. You print the value of the static field A.name, which belongs to the class

更多推荐

本文发布于:2023-07-27 15:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292456.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我在   时会   实例   发生   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!