equivalent to c++ "reference" or "pointers"

Steve Holden steve at holdenweb.com
Sun Jan 29 10:25:36 EST 2006


Collin Jones wrote:
> Hello,
> 
> Is there a Python equivalent to creating "reference" or "pointer"-type 
> variables as in C++??  I'm trying to create a couple classes that have 
> something like a container-and-iterator relationship; one class acts as 
> a data resource (container-like) and can be queried by multiple control 
> classes if needed (iterator-like).
> 
> If it's of any use, one class will contain all the frames of an 
> animation and its attributes, and the other will query the former for 
> image data and those attributes but control the actual animation process 
> on its own.
> 
> Here is a simple (albeit crappily written) example, in C++, of what I'm 
> trying to achieve.  Perhaps in Python I should be using a different 
> paradigm than this... that would be fine, as long as I can figure out 
> something that will serve my purpose.
> 
> #include <iostream>
> using namespace std;
> 
> class CrazyRes {
> private:
>     char *astring, *bstring;    
> public:
>     void setAString(char *s);
>     void setBString(char *s);
>     char *getAString() { return astring; }
>     char *getBString() { return bstring; }
> };
> void CrazyRes::setAString(char *s)
> {
>     astring = new char[255];
>     strcpy(astring, s);
> }
> void CrazyRes::setBString(char *s)
> {
>     bstring = new char[255];
>     strcpy(bstring, s);
> }
> 
> class CrazyCtrl {
> private:
>     CrazyRes *res;
>     public:
>     void attach(CrazyRes *r) { res = r; }
>     void printAString() { cout << res->getAString(); }
>     void printBString() { cout << res->getBString(); }
> };
> 
> int main()
> {
>     CrazyRes res;
>     CrazyCtrl ctrl;
>     
>     res.setAString("Hey! A-String!\n");
>     res.setBString("Whoa! B-String!\n");
>     
>     ctrl.attach(&res);
>     ctrl.printAString();
>     ctrl.printBString();
> 
>     return 0;
> }
> 
> I tried to keep this to the point... thanks in advance for any suggestions.
> 
Basically names are bound to values by reference in Python - a name, or 
an item in a "container" such as a list or a dictionary, is simply a 
reference to a value. Assignment binds a new item or name to an existing 
value.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list