python - 在 python 中使用另一个类的方法中的变量

标签 python class variables methods tuples

我的代码如下:

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/

相关文章:

python - Tkinter 菜单栏不显示在 Mac OS 上

java - 获取运行时创建的类

python - 如何根据另一个变量中的连续值在变量上应用函数

python - 访问元组中元素的时间复杂度

Python - 从变量中提取数据的正则表达式

找不到 PHP 命名空间类

C:在不使用全局变量的情况下,从创建的线程中操作在 main 中声明的结构

PHP,最好在if之前设置变量还是使用if/else?

Python Selenium WebDriver 在新版本(2.4.9)中无法执行 quit()

class - 如何在 Laravel 5 中添加我自己的自定义类?