获取另一个python代码中定义的变量值

时间:2014-04-02 21:46:45

标签: python

为了创建代码,我决定创建一个python类来定义一些默认值的变量。你可以在C中看到这个“结构”。

文件名称为:ScreenStructure.py

我已经定义了这段代码

class ViewIdleScreen():
    def _init_(self):
        self.menu_access = "id/no_id/21"
        self.Call_app = "id/no_id/23"
        self.Email_app = "idno_id/24"
        self.Camera_app = "id/no_id/27"
        self.Browser_app = "id/no_id/26"
        self.Contacts_app = "id/no_id/9"
        self.Calendar_app = "id/no_id/10"
        self.Messaging_app = "id/no_id/11"
        self.Notes_app = "id/no_id/12"

    def Call_app(self):
        return self.Call_app

在主文件中,我添加了:

from ScreenStructure import ViewIdleScreen

稍后在主文件的代码中:

IdleScreenView = ViewIdleScreen()
print IdleScreenView.Call_app()

但不显示“id / no_id / 23”,而是显示

<bound method ViewIdleScreen.Call_app of <ScreenStructure.ViewIdleScreen instance at 0x02A16990>>

2 个答案:

答案 0 :(得分:3)

首先,您要为__init__ _init_命名。这是错的。你需要两个下划线。

其次,您在那里设置属性Call_app,但其名称与您稍后定义的方法相同:

def Call_app(self):
    return self.Call_app

除了被属性遮蔽之外(如果__init__被正确声明),此方法返回方法本身,即您正在查看的bound method

避免属性和方法名称冲突,并正确命名__init__

答案 1 :(得分:0)

你不应该使命名与数据成员相同的函数

hello = "hello world"
def hello():
     print "goodbye!"

print hello

人们经常会在变量名前面加下划线或其他东西

class X:
    def __init__(self,*args):
         self._x = "yellow"
    def x(self):
       return self._x

但是@mhlester指出一个主要问题是您错误地命名了__init__