擅长:python、mysql、java
<pre><code>class check1:
def helloworld(self):
self.j = 5
check_instance=check1()
print (hasattr(check_instance,'j')) #False -- j hasn't been set on check_instance yet
check_instance.helloworld() #add j attribute to check_instance
print(check_instance.j) #prints 5
</code></pre>
<p>但是你不需要一个方法来给一个类实例分配一个新的属性。。。</p>
<pre><code>check_instance.k=6 #this works just fine.
</code></pre>
<p>现在可以像使用任何其他变量一样使用<code>check_instance.j</code>(或<code>check_instance.k</code>)。</p>
<p>这看起来有点像魔法,直到你知道:</p>
<pre><code>check_instance.helloworld()
</code></pre>
<p>完全等同于:</p>
<pre><code>check1.helloworld(check_instance)
</code></pre>
<p>(如果稍微考虑一下,这就解释了<code>self</code>参数是什么)。</p>
<p>我不完全确定您在这里要实现什么——还有一些类变量是由类的所有实例共享的。。。</p>
<pre><code>class Foo(object):
#define foolist at the class level
#(not at the instance level as self.foolist would be defined in a method)
foolist=[]
A=Foo()
B=Foo()
A.foolist.append("bar")
print (B.foolist) # ["bar"]
print (A.foolist is B.foolist) #True -- A and B are sharing the same foolist variable.
</code></pre>