python - 赋值前引用的局部变量 "age"

标签 python variables

<分区>

我最近开始学习python。我正在解决一个问题。

class Person:
    age = 0
    def __init__(self,initial_Age):
        if initial_Age<0:
            age=0
            print("This person is not valid, setting age to 0.")
        else:
            age = initial_Age

    def amIOld(self):
        if(age<13):
            print("You are young.")
        elif(age>=13 and age<18):
            print("You are a teenager.")
        else:
            print("You are old.")
    def yearPasses(self):
        age = age + 1
T=int(input())
for i in range(0,T):
age=int(input())         
p=Person(age)  
p.amIOld()
for j in range(0,3):
    p.yearPasses();        
p.amIOld();
print ("") 

我得到的错误显示如下:

Traceback (most recent call last):
File "solution.py", line 27, in <module>
p.yearPasses();        
File "solution.py", line 19, in yearPasses
age = age + 1 
UnboundLocalError: local variable 'age' referenced before assignment

输入如下:

4(Number of test cases)
-1
10
16
18

输出必须是这样的:

This person is not valid, setting age to 0.
You are young.
You are young.

You are young.
You are a teenager.

You are a teenager.
You are old.

You are old.
You are old.

你能指导我做错什么吗?。谢谢

最佳答案

在 python 中,你必须显式地使用 self 来访问实例属性:

class Person:
    def __init__(self, initial_Age):
        if initial_Age < 0:
            self.age = 0
            print("This person is not valid, setting age to 0.")
        else:
            self.age = initial_Age

    def amIOld(self):
        if self.age<13:
            print("You are young.")
        elif self.age>=13 and self.age<18:
            print("You are a teenager.")
        else:
            print("You are old.")

    def yearPasses(self):
        self.age += 1

关于python - 赋值前引用的局部变量 "age",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34908581/

相关文章:

c++ - 具有通用/模板化变量的 STL 容器

java - java中将字符串转换为变量

python - 打印枚举类的所有成员名称

python - 如何从点分隔的字符串列表重建 JSON?

Python关于字符编码的问题

python - 如何计算字符串中仍适用句点和结尾的单词的出现次数

variables - 如何在 PowerShell 中测试变量是否超过八个字符?

定义变量时复杂的从右到左规则

linux - 如何在 awk 命令中插入 shell 变量

python - Python 中多列之间的条件总和