4

I am not a programmer and I am trying to learn python at the moment. But I am a little confused with the object instantiation. I am thinking Class like a template and object is make(or instantiated) based on the template. Doesn't that mean once object is created(eg. classinst1 = MyClass() ), change in template shouldn't affect what's in the object?

In addition, the below code shows that I could change the class variable "common" but only if I haven't assign a new value to the "common" variable in the object. If I assign a new value to "common" in my object (say classinst1.common = 99), then change my class variable "common" no longer affect classinst.common value????

Can someone please clarify for me why the code below behave such way? Is it common to all OO language or just one of the quirky aspects of python?

===============

>>> class MyClass(object):
...     common = 10
...     def __init__(self):
...             self.myvar=3
...     def myfunction(self,arg1,arg2):
...             return self.myvar
... 
>>> classinst1 = MyClass()
>>> classinst1.myfunction(1,2)
3
>>> classinst2 = MyClass()
>>> classinst2.common
10
>>> classinst1.common
10
>>> MyClass.common = 50
>>> classinst1.common
50
>>> classinst2.common
50
>>> classinst1.common = 99
>>> classinst2.common
50
>>> classinst1.common
99
>>> MyClass.common = 7000
>>> classinst1.common
99
>>> classinst2.common
7000
4

1 回答 1

7

您对类声明和实例化有了大致的了解。但是您示例中的输出似乎没有意义的原因是实际上有两个变量称为common. 第一个是在代码顶部的类声明中声明和实例化的类变量。这是common您的大多数示例中唯一的。

当您执行此行时:

classinst1.common = 99

您正在创建一个对象变量,它是classinst1. 由于它与类变量具有相同的名称,因此它会隐藏或隐藏MyClass.common。现在所有进一步的引用classinst1.common都引用该对象变量,而所有要classinst2.common继续回退的引用,MyClass.common因为没有被调用的对象变量commonclassinst2.

所以当你执行时:

MyClass.common = 7000

这发生了变化MyClass.common,但classinst1.common仍然等于 99。在示例的最后几行中,当您向解释器询问 and 的值时classinst1.commonclassinst2.common前者指的是classinst1对象成员变量common,而后者指的是类变量MyClass.common

于 2013-06-12T22:14:42.997 回答