what *is* a class?

Matt Gerrans mgerrans at mindspring.com
Mon Jun 17 00:06:29 EDT 2002


> g = Group()

Now g is a reference to an instance, or object, of the class Group.

> what actually does Group() return and is there any way to get hold of
> that again?

It creates and returns an instance (or object, if you prefer) of the class
Group.   g is referring to that instance, so you haven't lost it, unless you
assign g to something else.   Since you have a reference to the object you
created (g), you don't need to "get ahold of it again" -- you still have a
hold of (on?) it.

> i want to write a method which returns the instance, so that f.e. the
> following is possible:
>
> g = Group()
> g2 = g.foobar()
> g2 is g
>
> so that g2 is identical to g.
> any idea?

All you need to do is this:

g2 = g

But if you insist on having a method to do it, you could define it like so:

class Group:
   # ... other code.
   def getRef(self):
      return self

Then, instead of "g2 = g", you could do this:

g2 = g.getRef()

I can't think of any reason why you would want to do this though, unless you
just need the extra typing practice and want to confuse someone who might be
reading the code...

Perhaps I misunderstand your question and what you want is a factory.   That
would be a method that creates and returns objects.   Of course, the
constructor does this, but you might want a factory if you will instantiate
different types of objects based on some runtime consideration.   If this is
what you are after, then reply to that effect for more elaboration.

- mfg





More information about the Python-list mailing list