“NameError:名称'self'未定义”

时间:2012-08-18 19:12:58

标签: python

我确定它与标签/空格有关,但100万美元的问题是程序中的位置???

import webapp2

form="""
<form method="post">
    What is your birthday?
    <br>

    <label> Month
    <input type="text" name="month">
    </label>

    <label> Day
    <input type="text" name="day">
    </label>

    <label> Year
    <input type="text" name="year">
    </label>
    <div style="color: red">%s(error)s</div>
    <br>
    <br>
    <input type="submit">
</form>
"""
months = ['January', 'Febuary','March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
mapping = dict((m[:3].lower(), m) for m in months)

def valid_month(month):
    if month:
        s_month = month[:3].lower()
        return mapping.get(s_month)

def valid_day(day):
    if day and day.isdigit():
        day = int(day)
        if day in range(1, 32):
            return day

def valid_year(year):
    if year and year.isdigit(): 
        int_year = int(year)
        if int_year in range(1900,2021): 
            return year

class MainPage(webapp2.RequestHandler):
    def write_form(self, error=""):
        self.response.out.write(form % {"error": error})

    def get(self):
        self.write_form()

    def post(self):
        user_month = valid_month(self.request.get('month'))
        user_day = valid_day(self.request.get('day'))
        user_year = valid_year(self.request.get('year'))

        if not (user_month and user_day and user_year):
            self.write_form("That's wasn't valid, friend!")
        else:
            self.response.write("Thanks! That's a totally valid day!")

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)            

2 个答案:

答案 0 :(得分:3)

python -tt会告诉你哪里。

$ python -tt script.py
  File "script.py", line xxx
    ...
TabError: inconsistent use of tabs and spaces in indentation

答案 1 :(得分:0)

您需要在类中定义valid_month,valid_day和valid_year。

当你打电话给他们时,你需要说

 user_month = self.valid_month(self.request.get('month'))

而不是

 user_month = valid_month(self.request.get('month'))

并且在每个方法的每个定义中,您需要包含'self'作为第一个参数,以便它将绑定到类:

def valid_month(self, month):

而不是

def valid_month(month):

否则,正在引用类的“self”对于在类范围之外存在的这些无关方法没有任何意义。