[Tutor] Accessing the name of an instance variable
Edward Comber
comber at cix.co.uk
Tue Nov 18 05:51:17 EST 2003
To explain why I want to this sort of thing - I have derived a simple
language for my partners to use in our medical practice by subclassing the
Python container classes. They don't program themselves but can easily
handle these classes which extract and manipulate groups of patients
depending on diseases.
A definition takes the form of..
non_smoker_group = DiseaseCode(['1371','137L','137P0','137S','137T'])
which extracts matching patients from the DB.
I want them to be able to do some simple debugging by outputting the
contents of the containers preceded by the container name, so they can check
that the codes they have used are correct (by doing a lookup in another DB).
I can do this of course by explicitly stating the container name:
describe_disease_group('non_smokerR',non_smoker_group)
but it would be nicer and more fool-proof to incorporate it in container
behaviour like
non_smoker_group.describe()
Eddie.
-----Original Message-----
From: Goncalo Rodrigues [mailto:op73418 at mail.telepac.pt]
Sent: 16 November 2003 14:33
To: Edward Comber; tutor at python.org
Subject: Re: [Tutor] Accessing the name of an instance variable
On Sun, 16 Nov 2003 13:53:41 -0000, you wrote:
>Thanks Goncalo. I have sorted something out with the below, but it won't
>work from another module (see further below).
>
>The purpose is to print a description of the objects created for third
party
>users of my code.
>
>Eddie.
>
>class A:
> def __init__(self,x,y):
> self.one = x
> self.two = y
>
> def describe(self):
> print 'Describing'
> this_instance = id(self)
> for name, instance in globals().items(): # vars()
> print name
> if isinstance(instance,A):
> if id(instance) == this_instance:
> print 'Description of', name
>
>#pp.pprint(read_code_helper.helper.description(self))
> print self.one, self.two
>
>if __name__ == '__main__' :
>
> a = A(1,2)
> b = A(1001,1002)
>
> a.describe()
> b.describe()
>
>
>import get_name
>
>a = get_name.A(1,2)
>
>a.describe() #dosen't pick up the name, presumably a scoping issue.
>
>
Yes, I forgot to add that globals is really only *module-level*
globals.
More information about the Tutor
mailing list