Tai*_*Tai 0 python syntax function
我最近开始使用 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'))
Run Code Online (Sandbox Code Playgroud)
但是,当我调用它时,出现以下错误:
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'))
Run Code Online (Sandbox Code Playgroud)
可以解决上述问题,但是在 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
} ]
Run Code Online (Sandbox Code Playgroud)
我有一个类似的错误,通过添加 self 无法解决:
File "/Users/tai/Desktop/FlashY/flashy/repository/mock.py", line 10, in __init__
myDate = getTodayDate()
NameError: global name 'getTodayDate' is not defined
Run Code Online (Sandbox Code Playgroud)
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
} ]
Run Code Online (Sandbox Code Playgroud)