【问题标题】:How do use the variable value in one method of class to another class in python [closed]python - 如何将一个类方法中的变量值用于python中的另一个类[关闭]
【发布时间】:2012-05-02 15:38:24
【问题描述】:

1) 我是 python 新手。我只是在一个类的方法中分配一个变量,并且该变量需要访问另一个类。 2)如何在python中将a方法从一个类调用到另一个类?

【问题讨论】:

  • 你能写下你试过的吗?
  • 我只写了两个类,在第一个类中我声明了一个变量 getdata = xxx。但我需要这个获取数据值到另一个类。怎么办。

标签: python


【解决方案1】:

我认为你正在尝试做这样的事情?

class one:
    def __init__(self):    
        self.x = 2
class two:
    def get1(self,reference):
        print reference.x

    def get2(self):
        global x
        print x.x
x = one()
y = two()
y.get1(x)
y.get2()

哪些输出:

2
2

【讨论】:

  • 谢谢,我如何从一个类调用一个方法到另一个类
  • 同理——你必须引用作为类实例的对象。 y 是第二类,所以 y.get1() 是 y 中的 get1 方法。
【解决方案2】:

更多信息会有所帮助,但这是一种方法。

class Foo(object):

    def __init__(self):
         self.value = "from Foo"

class Bar(object):

    def __init__(self):
        print Foo().value

Bar()

另一种口味

class Foo(object):

    def valuesForOtherClasses(self):
        self.value = "from Foo"

class Bar(Foo):

    def __init__(self):
        super(Bar, self).valuesForOtherClasses()
        print self.value

Bar()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多