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 containin
First, naming your arguments with uppercase letters is confusing. Since Python does not have formal, static type checking, we use the UpperCase
to mean a class and lowerCase
to mean an argument.
Second, we don't bother with CRoom and CPerson. Upper case is sufficient to indicate it's a class. The letter C isn't used. Room
. Person
.
Third, we don't usually put things in One Class Per File format. A file is a Python module, and we more often import an entire module with all the classes and functions.
[I'm aware those are habits -- you don't need to break them today, but they do make it hard to read.]
Python doesn't use statically defined types like C++. When you define a method function, you don't formally define the data type of the arguments to that function. You merely list some variable names. Hopefully, the client class will provide arguments of the correct type.
At run time, when you make a method request, then Python has to be sure the object has the method. NOTE. Python doesn't check to see if the object is the right type -- that doesn't matter. It only checks to see if it has the right method.
The loop between room.Room
and person.Person
is a problem. You don't need to include one when defining the other.
It's safest to import the entire module.
Here's room.py
import person
class Room( object ):
def __init__( self ):
self.nextId= 0
self.people= {}
def addPerson(self, firstName, secondName, gender):
id= self.NextId
self.nextId += 1
thePerson = person.Person(firstName,secondName,gender,id)
self.people[id] = thePerson
return thePerson
Works fine as long as Person is eventually defined in the namespace where this is executing. Person does not have to be known when you define the class.
Person does not have to be known until runtime when then Person(...) expression is evaluated.
Here's person.py
import room
class Person( object ):
def something( self, x, y ):
aRoom= room.Room( )
aRoom.addPerson( self.firstName, self.lastName, self.gender )
Your main.py
looks like this
import room
import person
r = room.Room( ... )
r.addPerson( "some", "name", "M" )
print r