1

我有这样的代码:

class A(object):  
    def __init__(self, master):  
        """Some work here"""  

    def do_this(self):  
        self.B = B.do_that()  
        print self.B[1]  


class B(object):  
    def __init__(self, master):  
        """Some work here"""  

    def do_that(self):  
        p = (1, 2)  

我不能让 A 类中的方法将该 self.B 用作元组。帮助。

4

2 回答 2

1

对于初学者,do_that()不返回任何东西。所以调用它几乎没有任何作用。

self.B = B.do_that()也不会工作。您必须首先创建该类的一个实例B

mything = B(your_parameters)
mything.do_that()

如果你希望它返回一些东西(即元组),你应该将你的更改do_that()为:

def do_that(self):  
    return (1, 2)

最后一点,这都可以通过继承来实现:

class A(B): # Inherits Class B
    def __init__(self,master):
        """Some work here""" 
    def do_this(self):
        print self.do_that()[1] # This is assuming the do_that() function returns that tuple

使用继承方法:

>>> class B:
...     def __init__(self, master):
...         """Some work here"""
...     def do_that(self):
...         return (1,2)
... 
>>> class A(B):
...     def __init__(self, master):
...         """Some work here"""
...     def do_this(self):
...         print self.do_that()[1] 
...
>>> mything = A('placeholder')
>>> mything.do_this()
2
于 2013-05-11T12:19:54.183 回答
0

首先,您必须在方法中将 B 实例化为 A 的属性A.do_this()。以下代码应该可以工作。

def do_this(self):
    b = B()
    self.B = b.do_that()  
    print self.B[1]  
于 2013-05-11T12:19:00.577 回答