使用 python 将 class 导入另一个文件时出错

Error importing class to another file with python

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

animal.txt

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

我创建的 class 文件名为 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

然后我想在文件中使用这个 class 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 : module 'pet' has no 'set_name' member.

如果我在 class 文件中执行以下代码 pet.py 我不会收到错误消息

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

并且returns符合预期

thing dog 10

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

我试过 pet=Pet() 但它有

error E0602: undefined variable 'Pet'

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

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

import pet

pet.Pet(...)

第二个要求您导入 Pet class

from pet import Pet

Pet(...)

这里要注意的是,根据您的文件夹结构,Python 可能无法将您的文件识别为可导入文件,因此您可能需要同时创建一个名为 __init__.py 的空白文件在目录结构中的位置为 pet.py.

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

import pet

myPet = pet.Pet()