Classes & Instances
Hans Nowak
wurmy at earthlink.net
Wed Jan 2 15:05:45 EST 2002
Andrew Nguyen wrote:
> 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. :-)
> 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()
> 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/
More information about the Python-list
mailing list