你能澄清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.nameprints:
B Aif 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 BEven 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 BCan 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 5So 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更多推荐
发布评论