class my_class():
args1=1
def fun(self):
print self.args1
my_c=my_class()
my_c.fun()
May I ask whether self.args1 is a class variable or an instance variable in the class inside? Can class variables be used with self.args1?
If we understand the class space and the instance space, the problem is very simple. Class has its own namespace and can be accessed through the
className.__dict__
See what’s inside. If an instance is instantiated, then the instance will have its own namespace to store its members, methods, etc. Of course, an instance can certainly share members of the class.
Specifically for your case, ifprint self.args1
First, it will look inside the namespace of the instance, but it is not found.args1
This member then continues to find the space of the class up and finds args1, which will output args1 of the class. but if there is an assignment statement, for exampleself.args1 = 1
, the instance creates args1 in its own space. Look at the following code:In [14]: class A(object): ....: args1 = 1 ....: def fun(self): ....: print self.args1 ....: def fun2(self): ....: self.args1 = 2 In [15]: a = A() In [16]: A.__dict__ # this is the namespace of the class and args1 can be seen in it Out[16]: # deleted some { 'args1': 1, 'fun': <function __main__.fun>, 'fun2': <function __main__.fun2>} In [17]: a. _ _ dict _ _ # while instance a does not have args1 in its namespace Out[17]: {} In [18]: a. fun () # executive func is a member of args1 that found the class. one In [19]: a. fun2 () # executes func2, which will create args1 in the instance space of a, independent of the class. In [20]: a. _ _ dict _ _ # can see that args1 already exists in a space. Out[20]: {'args1': 2} In [21]: if a. fun () # is executed again, the args1 of instance a will be directly output. 2. In [22]: Class A. Args1 # does not affect the space of the instance. Out[22]: 1 In [23]: the spaces between instances of b = a () # are also independent of each other. In [24]: b.args1 Out[24]: 1
Combined with the above code, should be able to understand from the relative essence