Python Modules and Classes?

Started by
1 comment, last by caldiar 16 years ago
Hey everyone. I'm currently working on adding support for some new hardware to the Python core of a game. The game is designed roughly like so: The main loop is compiled into a .pyd. The game core is a series of .py and .cpp/.h files. The hardware's SDK is a series of .cpp and .h files. I just started working with the source today and it's been quite some time since I've last used Python. I'm looking at the source and noticed something interesting. A module named App (which is the main loop and the functions main loop calls) is imported and is immediately put to work. The first line after the import is "App.InfMod = InfMod.blahblah" I mucked through the App code to find that InfMod doesnt exist. In fact, InfMod only exists in module InfMod. App is defined in the App module to be an externed class instance. So my question is this: Is it possible to add in new variables or even functions to a class instance on the fly? If I had a class called Cube and only an x and y variable, could I later declare z a variable by saying Cube.z = othermodule.init_z ? Any insight would be greatly appreciated. Thanks!
Advertisement
Yes, you can dynamically add class or instance attributes in this way, even methods with the help of the new module. There are times when this is useful, but I do want to caution that you probably shouldn't do it unless you have a real good reason. You don't want to get into a habit of using classes as "a bag of variables", as that is counter to object-oriented programming. Code which uses the class should be expecting a certain interface, and shouldn't have to use introspection to determine wether an attribute was or wasn't added before making use of it. And if you really do want a "bag of variables" there is the dictionary type for that.

Quote:If I had a class called Cube and only an x and y variable, could I later declare z a variable by saying Cube.z = othermodule.init_z ?


Yes, keeping in mind that the variable would be bound to the class, and thus shared by all instances. If you added it to an instance, only that instance would have it. You would have to replace the entire __init__ method for the class if you wanted all new instances to acquire their own non-shared attributes (pretty bad mojo if you ask me).
Thanks a ton Hollower that's exactly what I was looking for :)

This topic is closed to new replies.

Advertisement