简体   繁体   English

在Python中无法访问的函数-错误:未定义全局名称

[英]Function not accessible in Python - Error: global name is not defined

I'm new to Python programming and I'm stuck with the following error: 我是Python编程的新手,但遇到以下错误:

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>

    <br>
    <br>
    <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):

def get(self):
        self.response.out.write(form)

def valid_day(day):
        if day and day.isdigit():
            day = int(day)
            if day > 0 and day <= 31:
                return day

def valid_year(year):
        if year and year.isdigit():
            year = int(year)
            if year > 1899 and year < 2021:
                return year
def post(self):
        user_day = valid_day(self.request.get('day'))
        user_year = valid_year(self.request.get('year'))

I'm told that global name 'valid_day' is not defined. 有人告诉我未定义全局名称“ valid_day”。 Can anybody tell me where is the fault? 谁能告诉我哪里出问题了? I think I defined the function valid_day / valid_year above so it should be accessible, or not? 我想我在上面定义了函数valid_day / valid_year,因此应该可以访问或不能访问?

It appears by your use of self as a parameter to the post function that this code is inside a class. 通过使用self作为post函数的参数,该代码似乎在类内。

In that case, you need to use self to access the methods. 在这种情况下,您需要使用self来访问方法。 (Normally your assumption about scoping and defining functions above the call would be correct.) (通常,您对调用上方的作用域和定义函数的假设是正确的。)

Rewrite your post function as follows: 重写您的帖子功能,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM