gpt4 book ai didi

python - 在另一个类的类函数中使用变量(python)

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:44 24 4
gpt4 key购买 nike

我想在一个类的函数中使用我在另一个类中声明的变量。

例如我想在另一个类中使用变量“j”。是否可以? (我在某处读到它可能与实例变量有关,但完全无法理解这个概念)。

class check1:
def helloworld(self):
j = 5

最佳答案

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.

关于python - 在另一个类的类函数中使用变量(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com