python依赖模块_Python模块依赖性

Ok I have two modules, each containing a class, the problem is their classes reference each other.

Lets say for example I had a room module and a person module containing CRoom and CPerson.

The CRoom class contains infomation about the room, and a CPerson list of every one in the room.

The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.

The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(

In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:

class CPerson;//forward declare

class CRoom

{

std::set People;

...

Is there anyway to do this in python, other than placing both classes in the same module or something like that?

edit: added python example showing problem using above classes

error:

Traceback (most recent call last):

File "C:\Projects\python\test\main.py", line 1, in

from room import CRoom

File "C:\Projects\python\test\room.py", line 1, in

from person import CPerson

File "C:\Projects\python\test\person.py", line 1, in

from room import CRoom

ImportError: cannot import name CRoom

room.py

from person import CPerson

class CRoom:

def __init__(Self):

Self.People = {}

Self.NextId = 0

def AddPerson(Self, FirstName, SecondName, Gender):

Id = Self.NextId

Self.NextId += 1#

Person = CPerson(FirstName,SecondName,Gender,Id)

Self.People[Id] = Person

return Person

def FindDoorAndLeave(Self, PersonId):

del Self.People[PeopleId]

person.py

from room import CRoom

class CPerson:

def __init__(Self, Room, FirstName, SecondName, Gender, Id):

Self.Room = Room

Self.FirstName = FirstName

Self.SecondName = SecondName

Self.Gender = Gender

Self.Id = Id

def Leave(Self):

Self.Room.FindDoorAndLeave(Self.Id)

解决方案

No need to import CRoom

You don't use CRoom in person.py, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time".

If you actually do use CRoom in person.py, then change from room import CRoom to import room and use module-qualified form room.CRoom. See Effbot's Circular Imports for details.

Sidenote: you probably have an error in Self.NextId += 1 line. It increments NextId of instance, not NextId of class. To increment class's counter use CRoom.NextId += 1 or Self.__class__.NextId += 1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值