Skip to main content
 首页 » 编程设计

python之我的 Python 类中的奇怪行为

2025年05月04日12三少

所以这是不言自明的。

class Tray(object): 
    ''' 
    A class used to collect information about each unique tray 
    ''' 
    def __init__(self): 
        self.cycle = None 
        self.cell = None 
        self.bIsTilted = False # Assume trays are not tilted 
        self.bSendNoData = False # Assume data is sent, modified later if data not sent 
        self.trayData = (self.cycle, 
                         self.cell, 
                         self.bIsTilted, 
                         self.bSendNoData) 
 
    def __repr__(self): 
        return str(self.trayData) 
 
    def setCycle(self, cycle): 
        self.cycle = cycle 
 
    def setCell(self, cell): 
        self.cell = cell 

如果我运行以下语句:

currentTray = Tray() 
currentTray.setCycle(250) 
currentTray.setCell(300) 
print(currentTray) 
currentTray.setCell(25) 
print(currentTray.cell) 

我的输出是:

(None, None, False, False) 
25 

所以,我想我想弄清楚为什么我的 self.trayData 没有根据 self.cycle、self.cell 等中的值进行更新。这里有什么问题?

请您参考如下方法:

当您执行以下操作时 -

self.trayData = (self.cycle, 
                 self.cell, 
                 self.bIsTilted, 
                 self.bSendNoData) 

self.trayData 的第一个元素不指向 self.cycle (至少不是你想要的方式),它指向对象 self.cycle 指向 ,也就是None。因此,当您为 self.cycle 设置新值时,它不会自动反射(reflect)在 self.trayData 中。

要使您的特定情况起作用,最简单的方法是在 setCycle 和 setCell 方法中设置 trayData。

例子-

def setCycle(self, cycle): 
    self.cycle = cycle 
    self.trayData = (self.cycle, 
                 self.cell, 
                 self.bIsTilted, 
                 self.bSendNoData) 

或者您可以将 trayData 定义为属性,而不是在 __init__() 方法中定义它,Example -

class Tray(object): 
    ''' 
    A class used to collect information about each unique tray 
    ''' 
    @property 
    def trayData(self): 
        return (self.cycle, self.cell, self.bIsTilted, self.bSendNoData) 
    . 
    . 
    . #rest of the class. 

然后您可以使用 Tray().trayData 访问 trayData,使用 Tray 类的对象。

示例/演示 -

In [94]: class Tray(object): 
   ....:     @property 
   ....:     def trayData(self): 
   ....:         return (1,2,3,4) 
   ....: 
 
In [95]: t=Tray() 
 
In [96]: t.trayData 
Out[96]: (1, 2, 3, 4)