3 回答
TA贡献1784条经验 获得超2个赞
如果我理解你想要做什么:
class PersonInfo:
def __init__(self,name,age,height,hairColour):
self.name = name
self.age = age
self.height = height
self.hairColour = hairColour
def toList(self):
return [self.name, self.age, self.height, self.hairColour]
顺便说一下,类名的第一个字母总是大写。
编辑:要实现您想要做的事情:
old = PersonInfo("old", 1, 2, "blue")
new = PersonInfo(*old.toList())
new.name = "new"
print(old.name) #'old'
TA贡献1798条经验 获得超3个赞
使用复制模块:
函数 copy() 对任意 Python 对象的浅拷贝操作。
import copy
class PersonInfo:
def __init__(self, name, age, height, hair_colour):
self.name = name
self.age = age
self.height = height
self.hairColour = hair_colour
personArray = []
for x in range(20, 24):
personArray.append(PersonInfo("John", x, 6, "Brown"))
personStorage = copy.copy(personArray[2])
personStorage.name = "Ana"
print("\rpersonArray[2].name is %s\n"
"\rpersonStorage.name is %s"
% (personArray[2].name, personStorage.name))
TA贡献1898条经验 获得超8个赞
我已经创建了 setter 和 getter 来获取数据。此外,您还可以创建保存数据的实例的副本。
from copy import deepcopy
class PersonInfo:
def __init__(self,name,age,height,hairColour):
self.name = name
self.age = age
self.height = height
self.hairColour = hairColour
x = PersonInfo("Mario",34,1.70,"blue")
print(x.height) # prints 1.70
x1 = deepcopy(x)
print(x1.age)
添加回答
举报