在python中,我有一个包含列表作为其成员之一的类。
class fan_details:
name = ""
previous_addresses = []
age = 0
fans = []
x.name = "Joe Blow"
x.previous_address.append("4, seaview rd")
x.age = 42;
fans.append(x)
x.previous_address.pop(0)
x.name = "Jimmy Flag"
x.previous_address.append("21, Main Street")
x.age = 33;
fans.append(x)
print fans[0].previous_address
print fans[1].previous_address
最后两个印刷声明将打印出#34; 21,Main Street"。看起来append()就像C中的指针一样粉丝[0]。以前的地址和粉丝[1]。以前的地址相同。
有没有办法让粉丝[0] .previous_address保持在" 4,seaview rd"?
请耐心等待我,因为我是Python的菜鸟。
提前致谢。
答案 0 :(得分:2)
有一些问题:
固定代码:
class fan_details:
#you need to initialize and define the object:
def __init__(self, name="", previous_address = None, age = 0):
self.name = name
if previous_address is None:
self.previous_addresses = []
else:
self.previous_addresses = [previous_address]
self.age = age
fans = []
x = fan_details()
x.name = "Joe Blow"
x.previous_addresses.append("4, seaview rd")
x.age = 42;
fans.append(x)
#a python object is mutable!!! This means that "x" and fans[0] point to the same
#python object. Lets create a new python object:
x = fan_details(name = "Jimmy Flag", previous_address="21, Main Street", age=33)
#this line above is really important! Note that now we can initialize an object on one line :-)
fans.append(x)
print fans[0].previous_addresses
print fans[1].previous_addresses
答案 1 :(得分:1)
您的原始类未使用self
,因此所有变量都绑定到类定义并在所有实例中共享。
以下代码片段定义了__init__
方法作为构造函数。
class FanDetails():
def __init__(self, name="", previous_address=None, age=0):
self.name = name
self.previous_addresses = []
if previous_address:
self.previous_addresses.append(previous_address)
self.age = age
准备粉丝名单:
fans = []
现在的诀窍:为John创建一个FanDetails实例:
john = FanDetails("Joe Blow", "4, seaview rd", 42)
fans.append(john)
为吉米做同样的事情:
jimmy = FanDetails("Jimmy Flag", "21, Main Street", 33)
fans.append(jimmy)
与原始代码的主要区别在于,这些john和jimmy实例独立存在,每个实例的self
值不是在所有实例之间共享,而是实例隐私的根。
最后检查一下,这两个家伙真的不会分享更多,而不是合理:
print fans[0].previous_addresses
print fans[1].previous_addresses
你会看到:
['4, seaview rd']
['21, Main Street']
答案 2 :(得分:0)
我相信你有三个问题:
x
实例化为class
pop
任何内容我对代码的更改将如下所示:
class fan_details:
name = ""
previous_addresses = []
age = 0
fans = []
x = fan_details()
x.name = "Joe Blow"
x.previous_addresses.append("4, seaview rd") # <--- You had x.previous_address.append("4, seaview rd")
x.age = 42;
fans.append(x)
# x.previous_address.pop(0)
x = fan_details()
x.name = "Jimmy Flag"
x.previous_addresses.append("21, Main Street") # <--- You had x.previous_address.append("21, Main Street")
x.age = 33;
fans.append(x)
print fans[0].previous_addresses # add the 'es'
print fans[1].previous_addresses # add the 'es'
您需要在类定义中使用的变量名称和访问时使用的名称保持一致。
答案 3 :(得分:0)
列表是可变对象,因此不会分配新内存...复制x ...如果迭代...如果没有则使用不同的变量......
建议......请提供完整的代码(与问题相关)