Python无法导入nam

2024-06-16 09:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎不知道如何将两个类导入到彼此。当运行应用程序时,它简单地说

  from room import Room
ImportError: cannot import name Room

这可能是一个设计问题,但我不认为有其他方法可以引用这两个类,所以这需要保持原样。需要导入的唯一原因是对象中的redisco模块需要它们(它们需要知道类型)

^{pr2}$

我怎么才能让它工作?在

电子邮件:

框架是Redisco(Redis)


Tags: 模块对象方法namefromimport应用程序类型
3条回答

如果它们在同一个.py文件中,则不需要导入。如果它们在同一目录中的不同文件中,只需使用“import room”(假设它位于名为“import room”的文件中)房间.py'). 如果它们在不同目录中的不同文件中,则需要使用imp模块。在

import imp
roomClass = imp.load_source('roomClass', [Path to room.py])

然后可以用类似的方法调用它:

^{pr2}$

First of all if you want to import a module to your program, they must be in the same directory.

导入模块时按此操作

from filename import classname

Which is the filename= your .py file that you want to import class

class is the specific class that you want to use.

^{pr2}$

Which is going to add all functions and classes.

Also check this topic. program is running fine but cannot being import with IndexError

大多数ORM模型要么支持回引用(引用字段的目标模型被赋予一个指向引用对象的额外属性),要么允许您通过其他方式指定关系。在

Redisco没有我可以发现的反向引用,但是它支持字符串引用。如果传入一个字符串,它将被解释为与__name__属性匹配的模型名:

class Room(models.Model):
    players = models.ListField('Player', required = True)

这完全避开了进口问题。在

^{} docstring

target_type -- can be a Python object or a redisco model class.

If target_type is not a redisco model class, the target_type should also a callable that casts the (string) value of a list element into target_type. E.g. str, unicode, int, float.

ListField also accepts a string that refers to a redisco model.

code to resolve the name使用函数^{}解析字符串,该函数只搜索models.Model的所有子类,匹配__name__。在

它将在验证新值或第一次检索现有值时解析名称,此时Player子类已经导入。在

相关问题 更多 >