Reputation: 1256
I've started working with python recently and am totally confused.
I have the following class:
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'))
However when I call it I get the following error:
NameError: global name 'getTodayDate' is not defined
Why can I not access another function in the same class? I wrote this code in textMate, however I've never had issues accessing neighboring functions in the same class when working in Eclipse. Am I missing something?
def getTodayDate(self):
return str(datetime.now().strftime('%Y%m%d'))
def getTodayTime(self):
return str(datetime.now().strftime('%H%M%S'))
Works to solve the above problem however implementing it in init fails (Found thanks to answers):
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
} ]
I have a similar error that is not solved by adding self:
File "/Users/tai/Desktop/FlashY/flashy/repository/mock.py", line 10, in __init__
myDate = getTodayDate()
NameError: global name 'getTodayDate' is not defined
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
} ]
Upvotes: 0
Views: 3717
Reputation: 180411
Use self
in your method def getTodayDate(self):
andmyDate = self.getTodayDate()
Upvotes: 5