【问题标题】:Error importing class to another file with python使用python将类导入另一个文件时出错
【发布时间】:2019-03-24 21:46:46
【问题描述】:

我现在正在学习python 任务是这样的; 编写一个程序,从文件(称为 animals.txt)中读取宠物信息(名称、类型和年龄)并创建 Pet 对象(使用存储在 animals.txt 文件中的信息)。将 Pet 对象存储在名为 animals 的列表中。

animal.txt

ralph, dog, 3
buster, cat, 8
sammy, bird, 5
mac, dog, 1
coco, cat, 6

我创建的类文件被称为 pet.py

class Pet:
    # The __init__ method initializes the data attributes of the Profile class
    def __init__(self, name ='', animal_type = '', age = ''):
        self.__name = name
        self.__animal_type = animal_type
        self.age = 0

    def __str__(self):
        string = self.__name + ' ' + self.__animal_type + ' ' + self.age
        return string

    def set_name(self, name):
        self.__name = name

    def get_name(self):
        return self.__name

    def set_animal_type(self, breed):
        self.__animal_type = breed

    def get_animal_type(self):
        return self.__animal_type

    def set_age(self, old):
        self.age = old    

    def get_age(self):
        return self.age

然后我想在文件中使用这个类 animals.py

import pet

animals = [] // create a list 

infile = open("animals.txt", "r") // open the file

lines = infile.readlines() // read all lines into list

## add each pet object
for line in lines:
    data = line.split(",")
    animals.append(pet.set_name(data[0]))
    animals.append(pet.set_animal_type(data[1]))
    animals.append(pet.set_age(data[2]))

infile.close()

我收到一个错误

pet.set_name [pylint] E1101 : 模块 'pet' 没有 'set_name' 成员。

如果我在类文件 pet.py 中执行以下代码,我不会收到错误提示

pet = Pet()
name = "thing"
breed = "dog"
pet.set_name(name)
pet.set_animal_type(breed)
pet.set_age(10)
print(pet)

它按预期返回

东西狗 10

为什么 animals.py 文件不允许我使用已导入的类?

我试过 pet=Pet() 但它有

错误 E0602:未定义变量“宠物”

【问题讨论】:

  • from pet import Pet 然后像以前一样使用Pet

标签: python class object import instantiation


【解决方案1】:

现在您正在导入整个 pet 模块的内容。您可以通过以下两种方式之一访问Pet 类。

第一个要求你使用对象的整个虚线路径

import pet

pet.Pet(...)

第二个需要你导入Pet

from pet import Pet

Pet(...)

这里有个问题是,根据您的文件夹结构,Python 可能无法将您的文件识别为可导入文件,因此您可能需要在目录结构中与 @987654327 相同的位置创建一个名为 __init__.py 的空白文件@。

【讨论】:

    【解决方案2】:

    在你的animals.py 文件中pet 代表一个模块。您需要像这样提取位于该模块中的类:

    import pet
    
    myPet = pet.Pet()
    

    【讨论】:

    • TY .. 这确实有效,我知道我在那里做错了什么:-) 我现在打算将此数据附加到动物列表中.. 我想我会用 --> 动物做这个.append(myPet) 虽然 print(animals) 的输出是 --> 重复 5 次.. 当我在每次迭代中使用 print(myPet) 时,细节是正确的,但无法附加列表中的相同对象。
    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2023-02-08
    • 2019-02-21
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多