ensnare
ensnare

Reputation: 42113

Create a Python User() class that both creates new users and modifies existing users

I'm trying to figure out the best way to create a class that can modify and create new users all in one. This is what I'm thinking:

class User(object):

    def __init__(self,user_id):
      if user_id == -1
          self.new_user = True
      else:
          self.new_user = False

          #fetch all records from db about user_id
          self._populateUser() 

    def commit(self):
        if self.new_user:
            #Do INSERTs
        else:
            #Do UPDATEs

    def delete(self):
        if self.new_user == False:
            return False

        #Delete user code here

    def _populate(self):
        #Query self.user_id from database and
        #set all instance variables, e.g.
        #self.name = row['name']

    def getFullName(self):
        return self.name

#Create a new user
>>u = User()
>>u.name = 'Jason Martinez'
>>u.password = 'linebreak'
>>u.commit()
>>print u.getFullName()
>>Jason Martinez

#Update existing user
>>u = User(43)
>>u.name = 'New Name Here'
>>u.commit()
>>print u.getFullName()
>>New Name Here

Is this a logical and clean way to do this? Is there a better way?

Thanks.

Upvotes: 2

Views: 12783

Answers (5)

George Njue
George Njue

Reputation: 37

This one worked for me

class User:
    def __init__(self,username, password):
        self.username = username
        self.password = password



class UserManager:
    def __init__(self):
        self.users = {} # store new user to this dictionary


    def register_user(self, username, password):
        if username in self.users:
            print("User already exists")
        else:
            self.users[username] = User(username, password)
            print("User added successfully")

    def login_user(self, username, password):
        if username in self.users:
            user = self.users[username]
            if user.password == password:
                print("Login successful")
            else:
                print("Incorrect password")
        else:
            print("User not found")


    def main(self):
        print("Choose (1-3): ")
        print("1: Create User")
        print("2: Login account")
        print("3: Exit")

        is_running = True
        while is_running:

            choice = input("Welcome... Enter(1-3): ")

            if choice == '1':
                username = input("Enter a username: ")
                password = input("Enter a password: ")
                self.register_user(username, password)
            elif choice == "2":
                userlogin = input("Enter your username")
                userpass = input("Enter password")

                self.login(userlogin, userpass)
            elif choice == "3":
                is_running = False
                print("Welcome again...")
            else:
                print("Invalid choice... try again")

if __name__ == "__main__":
    user = UserManager()
    user.main()

Upvotes: 0

Yaroslav
Yaroslav

Reputation: 2736

What you are trying to achieve is called Active Record pattern. I suggest learning existing systems providing this sort of things such as Elixir.

Upvotes: 2

ychaouche
ychaouche

Reputation: 5092

You can do this with metaclasses. Consider this :

class MetaCity:
    def __call__(cls,name):
        “”“
            If it’s in the database, retrieve it and return it
            If it’s not there, create it and return it
        ““”
            theCity = database.get(name) # your custom code to get the object from the db goes here
            if not theCity:
                # create a new one
                theCity = type.__call__(cls,name)

        return theCity

class City():
    __metaclass__ = MetaCity
    name   = Field(Unicode(64))

Now you can do things like :

paris = City(name=u"Paris") # this will create the Paris City in the database and return it.
paris_again = City(name=u"Paris") # this will retrieve Paris from the database and return it.

from : http://yassinechaouche.thecoderblogs.com/2009/11/21/using-beaker-as-a-second-level-query-cache-for-sqlalchemy-in-pylons/

Upvotes: 4

Teddy
Teddy

Reputation: 6163

Off the top of my head, I would suggest the following:

1: Use a default argument None instead of -1 for user_id in the constructor:

def __init__(self, user_id=None):
    if user_id is None:
         ...

2: Skip the getFullName method - that's just your Java talking. Instead use a normal attribute access - you can convert it into a property later if you need to.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799270

Small change to your initializer:

def __init__(self, user_id=None):
      if user_id is None:

Upvotes: 1

Related Questions