2Q's: How to autocreate instance of class;How to check for membership in a class

George Sakkis george.sakkis at gmail.com
Tue Jun 17 07:36:55 CEST 2008


On Jun 16, 9:16 pm, asdf <a... at asdf.com> wrote:

> So I'm writing a script which will create several instances of User()
> class. I want each instance to be named after the login name
> of a user. I don't know beforehand how many users the script will
> have to create or how they are named. Right now I've created a dictionary
> of usernames as keys and objects themselves as values.

That's probably the most reasonable representation.

It works,
> but is very unwieldy, because every time I need to access a value from
> within an object I have to do something like dict-user[x].value.

It seems you are not aware of being able to name intermediate objects:

# name2user: mapping of names to User instances
for name in 'Bob', 'John', 'Sue':
    u = name2user[name]
    print u.value
    print u.password
    ...

In the sample above, u refers to whatever name2user[name] refers
(hopefully a User instance here), it does not create a copy. Therefore
after the assignment you can refer to the user as u instead of
name2user[name]. Not only this is easier to read but, unlike
statically typed languages, it is faster too. An expression such as
"a[b].c[d]" involves (at least) three method calls, so as long as it
doesn't change it is faster to compute it once, give it a name and
refer to the name afterwards.

> My second question is how can I check if object is a member of a class.
> so let's say I create a=User(), b=User()...
> Can I do something similar to
> if x.Users()==TRUE:
>         print "user already created"

I am not sure what you mean here. If you want to check whether a user
with a given name exists, look it up in the dictionary:

if 'Bob' in name2user:
  ...

If you ask how to check if some name x is a User instance, use the
isinstance() function:

if isinstance(x, User):
   print x.password

Checking for class membership though is usually considered unnecessary
or even harmful in Python. Just assume 'x' is a User and use it
anyway.

George



More information about the Python-list mailing list