我正在学习python 2.7并正在编写一个文本冒险游戏(比如Zork)来练习.我决定尝试以模块化的方式编写它,因为会有很多功能可以分成不同的文件以便组织和清晰.
在Windows 7上使用Visual Studio 2015,我制作了一个包含3个文件的解决方案:MainGame.py,Session.py和Verbs.py.
这里显示的是测试我是否可以将对象传递给分析播放器数据所需的函数.
Main.py
from Session import Session
from verbs import showX
s = Session()
showX(s)
Run Code Online (Sandbox Code Playgroud)
Session.py
class Session(object):
def __init__(self):
x = 5
def getX():
return x
Run Code Online (Sandbox Code Playgroud)
Verbs.py
def showX(s):
print s.getX()
Run Code Online (Sandbox Code Playgroud)
当我去运行时,我得到:
TypeError was unhandled by user code
getX() takes no arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
当我在showX中调用getX方法时,我希望不要传递任何东西,但我是.
我的问题是; 我传递的是什么?这种情况有什么问题?
类方法总是在调用开始时添加一个额外的参数,以表示调用该方法的对象.这就是为什么他们应该始终有一个self参数.
你可能想Session.py看起来像这样:
class Session(object):
def __init__(self):
self.x = 5
def getX(self):
return self.x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40 次 |
| 最近记录: |