我需要一些帮助来理解类的python作用域。
例如,这是一个非常有效的程序,这对我来说很有意义
import json
class Person(object):
def __init__(self, firstname, lastname, age,address):
self.firstname = firstname
self.age = age
self.lastname = lastname
self.address = address
class Address(object):
def __init__(self,zipcode,state):
self.zipcode = zipcode
self.state = state
personlist = []
for count in range(5):
address = Address("41111","statename")
person = Person("test","test",21,address)
print(count)
personlist.append(person)
jsonlist = []
for Person in personlist:
print Person.firstname
d = {}
d['firstname'] = Person.firstname
d['lastname'] = Person.lastname
d['age'] = Person.age
d['zipcode'] = Person.address.zipcode
d['state'] = Person.address.state
jsonlist.append(d)
jsondict = {}
jsondict["People"] = jsonlist
jsondict["success"] = 1
json_data = json.dumps(jsondict, indent =4)
print json_data
但是这个下一个程序给了我一个错误
import json
class Person(object):
def __init__(self, firstname, lastname, age,address):
self.firstname = firstname
self.age = age
self.lastname = lastname
self.address = address
class Address(object):
def __init__(self,zipcode,state):
self.zipcode = zipcode
self.state = state
def main():
personlist = []
for count in range(5):
address = Address("41111","statename")
person = Person("test","test",21,address)
print(count)
personlist.append(person)
jsonlist = []
for Person in personlist:
print Person.firstname
d = {}
d['firstname'] = Person.firstname
d['lastname'] = Person.lastname
d['age'] = Person.age
d['zipcode'] = Person.address.zipcode
d['state'] = Person.address.state
jsonlist.append(d)
jsondict = {}
jsondict["People"] = jsonlist
jsondict["success"] = 1
json_data = json.dumps(jsondict, indent =4)
print json_data
main()
我的问题是为什么在空白区域中创建类有效但在函数内创建它们无效。有没有办法在main函数中创建它们并且它有效?
编辑:
错误是 文件" jsontest.py",第9行,主要 person = Person(" test"," test",21,address) UnboundLocalError:局部变量' Person'在分配前引用
答案 0 :(得分:5)
问题是您使用的变量与您的班级Person
同名(也称为#34;阴影"):
for Person in personlist:
Python检测到您将其用作局部变量并引发错误:
UnboundLocalError:局部变量' Person'以前引用过 分配
表示您尝试在以下行中分配之前使用局部变量:
person = Person("test","test",21,address)
您可以找到有关它的更多信息here