Skip to main content
 首页 » 编程设计

python之子类化字典,类变量

2025年05月04日16dudu

我正在尝试拼凑一些示例代码,但遇到了一些对我来说不太有意义的问题。在不包括整个来源的情况下,我将尝试针对我认为重要的部分,希望我能得到所有内容。

在这里,他声明了一个自定义的 dict 子类,我认为应该是类变量“customer”和“film”。 (比如,从一个类中设置这些,应该在所有情况下更新它们,是吗?)

class Payment(dict): 
    customer = film = None 

这是他使用付款的地方...

columns = [item[0] for item in cursor.description] 
payments = [] 
for row in cursor.fetchall(): 
    payment = Payment(zip(columns, row)) #I believe this is where he loads dict items 
    payment.customer = customers[payment["customer_id"]] #This is where he assigns 'class variable' 
    payment.film = films[payment["film_id"]] 
    payments.append(payment) 

在最终列表中,所有的“支付”不应该具有相同的值(结果是另一个指令)?这就是我的困惑所在。

事实证明,这两个属性在所有方面都具有独特的值(value)。这与 Dict 的子类化有关吗?值是否被复制而不是被引用(因此从技术上讲它们是类变量,但由于它们被复制,它们继续保持唯一性)。

就在我以为我了解简单的 OO 机制时,这让我...

请您参考如下方法:

在以下内容中:

payment.customer = customers[payment["customer_id"]] #This is where he assigns 'class variable' 
payment.film = films[payment["film_id"]] 

您没有更改 payment.customer 和 payment.film 的值。相反,您要重新绑定(bind)它们,使它们特定于类的实例。

考虑以下示例:

class X(object): 
  val = ['orig'] 
 
x1 = X() 
x2 = X() 
x3 = X() 
x1.val = ['rebound']      # rebind 
x2.val[0] = 'modified'    # modify in place 
print x1.val, id(x1.val) 
print x2.val, id(x2.val) 
print x3.val, id(x3.val) 

这打印

['rebound'] 2907552 
['modified'] 2771544 
['modified'] 2771544 

观察 x1.val 在被反弹后如何变成一个完全独立的变量,而 x2.val 和 x3.val 继续两者引用同一个列表。