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

Mark Wooding mdw at distorted.org.uk
Tue Jun 17 11:25:02 EDT 2008


asdf <asdf at asdf.com> wrote:

(Presumably nothing to do with the Common Lisp system-definition utility.)

> So for example if I know that var1=jsmith. Can I somehow do
> var1=User().

Something like this might work.

class User (object):
  def __init__(me, name):
    me.name = name

class Users (object):
  def __getattr__(me, name):
    try:
      return object.__getattr__(me, name)
    except AttributeError:
      u = me.__dict__[name] = User(name)
      return u

>>> users = Users()
>>> alice = users.alice
>>> alice.name
'alice'
>>> alice is users.alice
True

Not very nice, though, and not particularly good at defending against
typos.

> 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()...

The built-in isinstance function seems an obvious choice.

-- [mdw]



More information about the Python-list mailing list