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

2024-03-29 00:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

Tags: 实例函数self声明概念def地方class
3条回答

使用类inheritane很容易“共享”实例变量

示例:

class A:
    def __init__(self):
        self.a = 10

    def retb(self):
        return self.b

class B(A):
    def __init__(self):
        A.__init__(self)
        self.b = self.a

o = B()
print o.a
print o.b
print o.retb()
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.

另一个类看不到j;但是,我认为您的意思是self.j,它可以。

class A(object):
    def __init__(self, x):
        self.x = x

class B(object):
    def __init__(self):
        self.sum = 0
    def addA(self, a):
        self.sum += a.x

a = A(4)
b = B()
b.addA(a)    # b.sum = 4

相关问题 更多 >