【发布时间】:2014-07-17 21:20:09
【问题描述】:
我最近开始使用 python 并且完全感到困惑。
我有以下课程:
class Vault:
def __init__(self):
# used to mock collection (table) of ads
self._ads = [ {
'id': '00000000-0000-0000-0000-000000000000',
'date': str(datetime.now().strftime('%Y%m%d')),
'time': str(datetime.now().strftime('%H%M%S')),
'source': 'chron.com',
'advertiser': 'itunes.apple.com',
'width': 300,
'height': 250
} ]
def get_ad_by_d(self, d):
myDate = getTodayDate()
ads = [ ad for ad in self._ads if ad['date'] == d ]
if len(ads) == 0:
return None
elif len(ads) >= 1:
return ads[0]
def getTodayDate():
return str(datetime.now().strftime('%Y%m%d'))
但是当我调用它时,我收到以下错误:
NameError:未定义全局名称“getTodayDate”
为什么我不能访问同一个类中的另一个函数?我在 textMate 中编写了这段代码,但是在 Eclipse 中访问同一类中的相邻函数时我从来没有遇到过问题。我错过了什么吗?
def getTodayDate(self):
return str(datetime.now().strftime('%Y%m%d'))
def getTodayTime(self):
return str(datetime.now().strftime('%H%M%S'))
可以解决上述问题,但在 init 中实施失败(感谢答案):
def __init__(self):
myDate = getTodayDate()
myTime = getTodayTime()
# used to mock collection (table) of ads
self._ads = [ {
'id': '00000000-0000-0000-0000-000000000000',
'date': myDate,
'time': myTime,
'source': 'chron.com',
'advertiser': 'itunes.apple.com',
'width': 300,
'height': 250
} ]
我有一个类似的错误没有通过添加self来解决:
File "/Users/tai/Desktop/FlashY/flashy/repository/mock.py", line 10, in __init__
myDate = getTodayDate()
NameError: global name 'getTodayDate' is not defined
cmets 中的解决方案:
def __init__(self):
myDate = self.getTodayDate()
myTime = self.getTodayTime()
# used to mock collection (table) of ads
self._ads = [ {
'id': '00000000-0000-0000-0000-000000000000',
'date': myDate,
'time': myTime,
'source': 'chron.com',
'advertiser': 'itunes.apple.com',
'width': 300,
'height': 250
} ]
【问题讨论】: