python在另一个函数中使用其他函数的变量_在另一个类中使用类函数中的变量(python)...

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值