Classes & Instances 
Author Message
 Classes & Instances

We all know that you can't use classes without instances.

Now, for the problem. How do I get a class, so that when an instance
is made of it, the class records the instance's name to a list.

e.g,
class a:
     pass

f = a

----

how do I get f into a list. And remember, my goal is _flexability_ so:

class a:
     pass

f = a

foolist = ['f']

Will NOT work for my goal, but, if let's say there is a function,
'TakeInstanceName()':

class a:
     foolist[:-1]=TakeInstanceName()#This function takes the Instance
name      #  whenever the class is refered to

f = a

#Now after that, foolist should have ['f'], but, my question is, what
IS the #function that would take the TakeInstanceName()'s place?
-----



Mon, 21 Jun 2004 03:00:27 GMT  
 Classes & Instances


Quote:
> We all know that you can't use classes without instances.

> Now, for the problem. How do I get a class, so that when an instance
> is made of it, the class records the instance's name to a list.

> e.g,
> class a:
>      pass

> f = a

I assume you means "f = a()" here. If so, you probably want something like:

Quote:
>>> class A:

...  instances = []
...  def __init__(self, name):
...   self.instances.append(self)
...   self.name = name
...  def __repr__(self):
...   return '<instance %s>' % self.name # Name is only around so this
prints something legible
...
Quote:
>>> f = A('spam')
>>> g = A('eggs')
>>> h = A('more spam')
>>> A.instances

[<instance spam>, <instance eggs>, <instance more spam>]

You don't have to make instances a part of the class A, but that's what I'd
do.

-tim

Quote:
> ----

> how do I get f into a list. And remember, my goal is _flexability_ so:

> class a:
>      pass

> f = a

> foolist = ['f']

> Will NOT work for my goal, but, if let's say there is a function,
> 'TakeInstanceName()':

> class a:
>      foolist[:-1]=TakeInstanceName()#This function takes the Instance
> name      #  whenever the class is refered to

> f = a

> #Now after that, foolist should have ['f'], but, my question is, what
> IS the #function that would take the TakeInstanceName()'s place?
> -----



Mon, 21 Jun 2004 03:26:03 GMT  
 Classes & Instances
original post essentially asked:

        how do I get an instance's name?

pseudocode:

  class A:
    def instanceName(self):pass

  f = a()

  print f.instanceName # should print "f"

a tangential suggestion might be to look into implementing one of the
creational patterns from GoF in python to control the creation of class
instances, thereby allowing you to keep track of them.

// mark



Mon, 21 Jun 2004 03:35:29 GMT  
 Classes & Instances
Tim Hochberg:

[snip]

Quote:
> ...  def __init__(self, name):

original poster may complain that this requires the following inelegance:

        f = a('f')

// mark



Mon, 21 Jun 2004 03:37:35 GMT  
 Classes & Instances
class a:
    pass

f = a()

for k in locals().keys():
    if isinstance(locals()[k], a):
        print k

This probably isn't what you want.  I can't help but wonder what problem
you're trying to solve?

Maybe this is an area where metaclasses would help?

// mark



Mon, 21 Jun 2004 03:23:07 GMT  
 Classes & Instances
May be this will be helpfull for you
Quote:
>>> class Obj:

        def Class(self):
                return Obj

Quote:
>>> f = Obj()
>>> f_class = f.Class()
>>> f_class

<class __main__.Obj at 0x0092C7D8>
Quote:
-----Original Message-----

Sent: Wednesday, January 02, 2002 9:00 PM

Subject: Classes & Instances

We all know that you can't use classes without instances.

Now, for the problem. How do I get a class, so that when an instance
is made of it, the class records the instance's name to a list.

e.g,
class a:
     pass

f = a

----

how do I get f into a list. And remember, my goal is _flexability_ so:

class a:
     pass

f = a

foolist = ['f']

Will NOT work for my goal, but, if let's say there is a function,
'TakeInstanceName()':

class a:
     foolist[:-1]=TakeInstanceName()#This function takes the Instance
name      #  whenever the class is refered to

f = a

#Now after that, foolist should have ['f'], but, my question is, what
IS the #function that would take the TakeInstanceName()'s place?
-----
--
http://mail.python.org/mailman/listinfo/python-list



Mon, 21 Jun 2004 03:42:20 GMT  
 Classes & Instances

Quote:

> We all know that you can't use classes without instances.

Sure you can:

    class Options:
        readonly = 0
        verbose = 0

    if something: Options.verbose = 1

Useful if you want a pseudo-singleton struct. :-)

Quote:
> Now, for the problem. How do I get a class, so that when an instance
> is made of it, the class records the instance's name to a list.

> e.g,
> class a:
>      pass

> f = a

Note that this does not create an instance of a. The correct syntax
is:

    f = a()

Quote:
> how do I get f into a list.

Instances, unlike classes, do not have an inherent name. Code like

    x = y = z = a()

creates three equally valid names for the same instance of a. None
of these is the "real" name of the instance.

The following code uses a class that has a list of names, shared
between instances. You'll need to explicitly name the class, though,
for reasons mentioned above (the name of an instance is whatever
name(s) you define for it in the namespace). So you'll need to
do something like

   foo = B(1, "foo")

(The value, 1, isn't necessary, but I added it to the class to make
it a bit more real-life. :-)

#---begin---

class B:
    names = []
    def __init__(self, value, name):
        self.value = value
        self.name = name
        B.names.append(name)
    def __del__(self):
        B.names.remove(self.name)

foo = B(1, "foo")
bar = B(2, "bar")
baz = B(3, "baz")

print B.names
del foo
print B.names

#---end--

HTH,

--Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==\n')
       # decode for email address ;-)
Site:: http://www.awaretek.com/nowak/



Mon, 21 Jun 2004 04:05:45 GMT  
 Classes & Instances

Quote:
> Now, for the problem. How do I get a class, so that when an instance
> is made of it, the class records the instance's name to a list.

Python objects do not have 'a name'.  Rather, 0 to n names can be
bound to any object.  Functions, classes, and modules have
definition_names which may or may not correspond to any names
currently bound to the object.  As others have pointed out, if you
want instances to also have a definition name, you will have to pass
in into __init__ and set it explicitly.

Terry J. Reedy



Mon, 21 Jun 2004 04:50:57 GMT  
 Classes & Instances

Quote:
> original post essentially asked:

> how do I get an instance's name?

> pseudocode:

>   class A:
>     def instanceName(self):pass

>   f = a()

>   print f.instanceName # should print "f"

> a tangential suggestion might be to look into implementing one of the
> creational patterns from GoF in Python to control the creation of class
> instances, thereby allowing you to keep track of them.

You need no such complication to "keep track of" a class's instances --
it's easy and idiomatic to do it e.g. by appending a reference (I'd
suggest a weakref) to a per-class list in the instance's __init__, for
example.

This has nothing to do with *NAMES*, and the fact that the original
poster's request, properly translated into "how do I get the name
to which, in the future, the instance that is being created right
now will be bound" has no Python solution.  First of all, Guido would
have to insert in Python his beloved time machine, because, as the
instance is being created, no name yet is bound to it.  Even that
would not make things SIMPLE -- what "name" should be returned in
the case of
    somelistorother.append(a())
or
    x=y=z=t=a()
or
    f(a(),a(),a(),a())
or...?!

The only solution is apparently an exhaustive search, AFTER the
binding has taken place, into all possile "names" that MIGHT now
be bound to the generated instance (some careful definition will
be needed regarding attributes, since of course after
    x.y = a()
there's no guarantee whatsoever that x.y is bound to the same
object... maybe x.ZZZ might now be, or ...).

It's not worth it.  Maybe in some kind of debugging mode for a
development-environment, but I have my doubts even then.

Alex



Mon, 21 Jun 2004 21:37:52 GMT  
 Classes & Instances
I actually have the same problem in my application (I am actually trying to
represent some various pieces of information with a Python program).
My conclusion is that the right way to do it is to overload the globals()
or locals() dictionary, such as :

class NamingDict(dict):
        def __setitem__(self,key,val):
                try:
                        val.name=key
                except: pass
                dict.__setitem__(self,key,val)

class Foo: pass

d=NamingDict({"a":Foo()})
exec "b=a;print 'a has name :','name' in dir(a)" in d,None

but it prints : "a has name : 0" instead of  "a has name : 1"

I cannot retrieve the reference, but I understood that this feature was
considered normal by Guido, although he has optimization problems for
local accesses.

The current situation is that this works neither with locals nor globals,
and the reason is that the Python interpreter directly calls the dict
method, even if the globals() dict has overridden methods (for locals, it
is even more optimized).

I have a very simple patch to the interpreter to make things work with
globals (no measurable performance impact)
and the situation is significantly more complex for locals but I
think I can come to an implementation in which performance is not
degraded in the normal case (i.e. when locals() is a plain dict) and in
which the full semantic of exec and eval is ensured.

Because I think that people needing this feature are the exceptions more
than the rule, I do not expect anyone to actually update the interpreter.

My question now is : how do I propose a patched interpreter so that it
becomes (if accepted, of course) integrated in a future release (note that
this is more a bug fix than a new feature) ?

Note also that you cannot set the local dictionary of a function call
through exec. For example :

def foo():
        try:
                print "x = %s"%x
        except:
                print "x is not set"
        x=0 # make x a local variable

exec foo.func_code in {"x":1} # set both locals and globals

outputs : "x is not set" instead of "x = 1"

This also should be fixed and I am prepared to do the work as well.



Quote:


>> original post essentially asked:

>> how do I get an instance's name?

>> pseudocode:

>>   class A:
>>     def instanceName(self):pass

>>   f = a()

>>   print f.instanceName # should print "f"

>> a tangential suggestion might be to look into implementing one of the
>> creational patterns from GoF in Python to control the creation of class
>> instances, thereby allowing you to keep track of them.

> You need no such complication to "keep track of" a class's instances --
> it's easy and idiomatic to do it e.g. by appending a reference (I'd
> suggest a weakref) to a per-class list in the instance's __init__, for
> example.

> This has nothing to do with *NAMES*, and the fact that the original
> poster's request, properly translated into "how do I get the name to
> which, in the future, the instance that is being created right now will
> be bound" has no Python solution.  First of all, Guido would have to
> insert in Python his beloved time machine, because, as the instance is
> being created, no name yet is bound to it.  Even that would not make
> things SIMPLE -- what "name" should be returned in the case of
>     somelistorother.append(a())
> or
>     x=y=z=t=a()
> or
>     f(a(),a(),a(),a())
> or...?!

> The only solution is apparently an exhaustive search, AFTER the binding
> has taken place, into all possile "names" that MIGHT now be bound to the
> generated instance (some careful definition will be needed regarding
> attributes, since of course after
>     x.y = a()
> there's no guarantee whatsoever that x.y is bound to the same object...
> maybe x.ZZZ might now be, or ...).

> It's not worth it.  Maybe in some kind of debugging mode for a
> development-environment, but I have my doubts even then.

> Alex



Mon, 28 Jun 2004 22:34:34 GMT  
 Classes & Instances

    ...

Quote:
> My question now is : how do I propose a patched interpreter so that it
> becomes (if accepted, of course) integrated in a future release (note that
> this is more a bug fix than a new feature) ?

You can submit a patch (a context-diff) to python.sourceforge.net.

Alex



Tue, 29 Jun 2004 00:34:08 GMT  
 Classes & Instances

Quote:

> May be this will be helpfull for you
> >>> class Obj:
>    def Class(self):
>            return Obj

> >>> f = Obj()
> >>> f_class = f.Class()
> >>> f_class
> <class   main  .Obj at 0x0092C7D8>

What's wrong with

Quote:
>>> f_class = f.__class__

???


Tue, 29 Jun 2004 18:38:16 GMT  
 
 [ 12 post ] 

 Relevant Pages 

1. Classes & Instance Names Spaces

2. instances of classes and instances of instances

3. Instance of class as a class

4. Can a class instance also be a class?

5. Classes - instance/class, methods/members, inheritance and best p ractices

6. Comparing class instance with class

7. Problem with calling instance of one class from another class

8. repeated class redefinition and update-instance-for-redefined-class

9. Classes - instance/class, methods/members, inheritance and be st practices

10. Class vs Instance methods

11. Strange instance class valiable behavior

12. Breakpoints per Class or Instance

 

 
Powered by phpBB® Forum Software