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
但你并不需要的方法,以一个新的属性分配到一个类的实例...
check_instance.k=6 #this works just fine.
现在你可以使用check_instance.j(或check_instance.k)就像你使用任何其他变量。
这可能看起来像魔术一点点,直到你学会说:
check_instance.helloworld()
完全等同于:
check1.helloworld(check_instance)
(如果你想想看一点点,那说明什么参数是self)。
我不能完全确定你想要什么在这里实现 - 还有一些是由类的所有实例共享类变量...
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.