我要做的是使用python序列化一些类对象。但是,当我尝试迭代类对象的list属性时,我得到一个str错误。我不清楚如何解决这个问题。我对python很新。
AttributeError:'str'对象没有属性'serialize'
此函数内的Family类对象内发生错误...
for member in self.members:
print member
data["members"].append( member.serialize() ) # ERROR
代码
import json
# Functions
# ------------------------------------------------------------------------------
def GetProperties(properties):
if properties == "Basic Properties":
return {
"Basic Properties" : [
Property("isMale", False),
Property("isRelated", True),
]
}
elif properties == "Extra Properties":
return {
"Extra Properties" : [
Property("isTall", False),
Property("isAthletic", True),
]
}
# Classes
# ------------------------------------------------------------------------------
class Property:
def __init__(self, key, value):
self.key = key
self.value = value
class Person:
def __init__(self, name, attributes={}):
self.name = name
self.attributes = {}
def serialize(self):
data = {
"classname" : self.__class__.__name__,
"name" : self.name,
"attributes" : {},
}
return data
class Family:
def __init__(self, name, members=[], attributes={}):
self.name = name
self.members = members[:]
self.attributes = {}
def serialize(self):
data = {
"classname" : self.__class__.__name__,
"name" : self.name,
"attributes" : {},
"members" : [],
}
for member in self.members:
print member
data["members"].append( member.serialize() )
return data
# testing Serialization
newPerson = Person( "Joey" )
newPerson.attributes.update( GetProperties( "Basic Properties" ) )
newFamily = Family( "Johnson's" )
newFamily.attributes.update( GetProperties( "Basic Properties" ) )
newFamily.members.append( "newPerson" )
data = newFamily.serialize()
json.dump(data, open("test.json",'w'), indent=4)
答案 0 :(得分:1)
尝试:
newFamily.members.append( newPerson) # newPerson as the object instantiated in preceding lines
在原始代码中,您有:
newFamily.members.append("newPerson") # newPerson as a string literal
因此,传递字符串,您正在尝试序列化字符串,而不是Person
对象。