【问题标题】:Objects being created from a txt file with the wrong attribute types?从具有错误属性类型的 txt 文件创建的对象?
【发布时间】:2022-01-19 16:07:52
【问题描述】:

我有一个格式化的 txt 文件 (P001, Part001, 10.0, 100 OR AP002, AssembledPart2, 130, 1, P002, P004) 正在逐行读取,每一行都被创建为一个对象。这一切似乎工作正常,但所有属性都设置为 str,我需要其中一些是 float 或 int。我不知道为什么会这样。

def readParts(self, file):
    '''Reads the parts.txt file and runs it line by line thru part.__init__ and adds to parts list
    '''
    id = None
    name = None
    price = 0.0
    onhandqty = int
    componentID1 = None
    componentID2 = None
    with open(os.path.join(sys.path[0],"parts.txt"), "r") as file:
        for line in file:
            row = line.split(",")
            if len(row) == 4:
                id, name, price, onhandqty = [i.strip() for i in row]
                part = Part(id, name, price, onhandqty)
                WarehouseManager.parts.append(part)
            if len(row) == 6:
                id, name, price, onhandqty, componentID1, componentID2 = [i.strip() for i in row]
                assembledpart = AssembledPart(id, name, price, onhandqty, componentID1, componentID2)
                WarehouseManager.parts.append(assembledpart)

作为参考,类 init

class Part():

    id = None

    name = None

    price = 0.0

    onhandqty = int



    def __init__(self, id, name, price, onhandqty):
        self.id = id
        self.name = name
        self.price = price
        self.onhandqty = onhandqty
class AssembledPart(Part):
    

    componentID1 = None

    componentID2 = None



    def __init__(self, id, name, price, onhandqty, componentID1, componentID2):
        super().__init__(id, name, price, onhandqty)
        self.componentID1 = componentID1
        self.componentID2 = componentID2

谁能指出我哪里出错了?

【问题讨论】:

    标签: python class oop attributes init


    【解决方案1】:

    如果您将print(type(onhandqty)) 传递给Part 构造函数,您会看到它是str。如果您希望它成为Part 对象中的int,那么您需要在将其传递给构造函数之前对其进行强制转换。

    在类中设置onhandqty = int 不会强制传入的值为int

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2017-11-12
      相关资源
      最近更新 更多