我如何访问变量从一个类到另一个? [英] How would I access variables from one class to another?

查看:107
本文介绍了我如何访问变量从一个类到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个利用多个类的程序。我有一个类专门用于确定一组变量的值。然后我想能够访问这些变量的值与其他类。我的代码如下:

I am writing a program that is utilizing multiple classes. I have one class that is dedicated to determining values for a set of variables. I would then like to be able to access the values of those variables with other classes. My code looks as follows:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1


class ClassB(ClassA):
    def __init__(self):
        self.var1 = ?
        self.var2 = ?

object1 = ClassA()
sum = object1.methodA()
print sum

我使用classA来初始化2个变量(var1和var2)。然后使用methodA添加它们,保存结果为var1(我认为这将使var1 = 3和var2 = 2)。我想知道的是我将如何让ClassB然后能够从ClassA获取var1和var2的值。

I use classA to initialize 2 variables (var1 and var2). I then use methodA to add them, saving the result as var1 (I think this will make var1 = 3 and var2 = 2). What I want to know is how would I have ClassB then be able to get the values for var1 and var2 from ClassA?

推荐答案

var1 var2 实例变量。这意味着你必须发送 ClassA 的实例到 ClassB ,以便ClassB访问它,即: / p>

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1



class ClassB(ClassA):
    def __init__(self, class_a):
        self.var1 = class_a.var1
        self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

另一方面 - 如果你使用类变量,您可以访问var1和var2,而不将object1作为参数发送到ClassB。

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
    var1 = 0
    var2 = 0
    def __init__(self):
        ClassA.var1 = 1
        ClassA.var2 = 2

    def methodA(self):
        ClassA.var1 = ClassA.var1 + ClassA.var2
        return ClassA.var1



class ClassB(ClassA):
    def __init__(self):
        print ClassA.var1
        print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

但是,请注意,类变量在其类的所有实例之间共享。

Note, however, that class variables are shared among all instances of its class.

这篇关于我如何访问变量从一个类到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆