我的代码如下:
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 作为元组。帮助。
最佳答案
对于初学者来说,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
关于python - 在 python 中使用另一个类的方法中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496956/