473,398 Members | 2,427 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

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

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. 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.
Is there a way of automatically naming objects from variable names.
So for example if I know that var1=jsmith. Can I somehow do
var1=User(). This obviously won't work because I tried this. It'll just
create var1 of type User.

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"

Right now I'm doing this using try-except which works
but I'm looking for something cleaner.

thanks for all the replies.
Jun 27 '08 #1
2 1067
On Jun 16, 9:16*pm, asdf <a...@asdf.comwrote:
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
Jun 27 '08 #2
asdf <as**@asdf.comwrote:

(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]
Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: MKoleoso | last post by:
Problem: C#- Unable to create instance of a class implementing from an interface I have: namespace someNamespace { public __gc class SomeClass1 { }
5
by: Darren Grant | last post by:
Hi there, I've attempted to implement an Angle class. An Angle is a subset of an integer, where the range is [0,360). All other operations should be permitted. The code works, I think......
1
by: John C | last post by:
Hi, I am trying to include the generation of random numbers in my c++ class. However I don't quite know how to incorporate it. To start with, I managed to get random numbers going via the...
3
by: DraguVaso | last post by:
Hi, I'm having the following situation: - A class clsFournisseur with public property's which raise a MyPropertyChanged-event in the Set-method for each Property. Public Event NomChanged As...
2
by: Earl Teigrob | last post by:
I am programming ASP.NET using C#. I have been accessing static variables accross my entire application but now need to change some of the static variables that are session specific to instance...
3
by: Jarod | last post by:
Hey I would like to write a database class. Let's say it would work like this: datareader GetDataReader(string sqlquery); This would be static, so I could do this: datareader dr =...
6
by: Tim Mulholland | last post by:
I have created my own IIdentity class (actually inherited from GenericIdentity) to contain lots of extra useful information to be passed around with the user's basic information. The class...
6
by: Shimon Sim | last post by:
Hi I am working on application that need to hold custom user information - Last and first name, email, some other domain related information. I used to create Base class for all my pages. The base...
2
by: ali | last post by:
Hi, I have a question with regards to abstract classes (understanding that I cannot instantiate an abstract class). If my Abstract base class has: private: int width; int height;
1
by: aj | last post by:
SQL Server 2005 I have an empty named instance on my SQL Server 2005 server. Not the default instance, but a secondary named instance. I would like to completely delete this named instance w/o...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.