Python Forum

Full Version: Classes and Functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
So I understand little about classes and functions. I know how to create simple classes and functions but I still need much help and learning. I am trying to create a login file for a game that I will start working on as soon as my login modules are finished and working properly. This code is examples of what I've created and learned while making simple classes:


from random import randint

class Die:

   def __init__(self, sides, roll=0):
       self.sides = sides
       self.roll = roll

   def roll_die(self):
       if self.sides==6:
           while self.roll < 6:
               print("You roll a six sided die: " + str(randint(1, 6)))
               self.roll += 1
       elif self.sides==10:
           while self.roll < 6:
               print("You roll a ten sided die: " + str(randint(1, 10)))
               self.roll += 1
       elif self.sides==20:
           while self.roll < 6:
               print("You roll a twenty sided die: " + str(randint(1, 20)))
               self.roll += 1
       else:
           print("Mistakes have been made!")


six_sided_die = Die(6)
six_sided_die.roll_die()
print('')
ten_sided_die = Die(10)
ten_sided_die.roll_die()
print('')
twty_sided_die = Die(20)
twty_sided_die.roll_die()
class User():

   def __init__(self, first_name, last_name, username):

       self.first_name = first_name

       self.last_name = last_name

       self.username = username



   def describe_user(self):

       print("\nThis is the information for " + self.username + ":\n-- Last name, First name --\n\t* " +

             self.last_name.title() + ", " + self.first_name.title())



   def greet_user(self):

       print("\nHello, " + self.username + "!")



user_1 = User('joshua', 'mitchum', 'Broodwar1998')

user_2 = User('loki', 'thor', 'Godz')



user_1.describe_user()

user_1.greet_user()



user_2.describe_user()
user_2.greet_user()
Ok so that's my knowledge as far as classes go... Now what I need help with is turning this next code into a class. I know how to make classes without taking in user input. I do not know how to implement user input into classes. For example this code:

prompt_message = "Enter the username you wish to create. \nType \'quit\' if you wish to exit: "

prompt_username = ""



while prompt_username.lower() != 'quit':

   prompt_username = input(prompt_message)



   if prompt_username.lower() == 'quit':

       break

   else:

       print("Welcome to a whole new world, " + prompt_username)
       break
I understand I need to create a list of usernames input and save it to a txt file or json file as a dictionary so i can recall it everytime a username is created in order to check if the username is available and passwords match also length restrictions and password hashing... But for now I just need to understand how to turn this into a simple class if that's possible? To make this more efficient code I guess?
I would put it into a method of the class, if it has to be a class:

class Prompter(object):

    def __init__(self, prompt_message):
        self.prompt_message = prompt_message

    def main(self):
        prompt_username = input(self.prompt_message)
        if prompt_username.lower() != 'quit':
            print('Welcome to a whole new world, {}.'.format(prompt_user_name))
I took out the loop since there didn't seem to be any point to it (you break out of it no matter what the input is). If the loop is meant to be expanded on as you develop the program, you can just put the whole loop into the main method. To use it, just instantiate and call:

prompter = Prompter("Enter the username you wish to create. \nType 'quit' if you wish to exit: ")
prompter.main()
Note that you don't need to backslash single quotes if you are using double quotes to define the string constant.
I have not learned about the .format() function yet. Would you please explain. I do see the point about taking the loop out. I do apologize I am new to coding so I feel my codes will have a bunch of code that is pointless and more efficient code can take it's place a lot of times I'm sure. I mean to put the method prompter into a class called Login(). When you use the class Prompter(object), I have never seen a class given the argument "object". What does this do?

Another thing... How do I store the username input by the user in a file. Ex:

prompt_message = "Enter the username you wish to create. \nType \'quit\' if you wish to exit: "

prompt_username = ""

while prompt_username.lower() != 'quit':
    prompt_username = input(prompt_message)

    if prompt_username.lower() == 'quit':
        break
    else:
        print("Welcome to a whole new world, " + prompt_username)
        filename = 'guest_book.txt'

        with open(filename, 'a') as file_obj:
            file_obj.write(prompt_username + '\n')
        break
Almost everything in Python is an object. Any string is an object from class 'str'.

>>> type("A string or something")

<class 'str'>
This object may have methods and attributes.
You can see all methods of a str object using dir() built-in function.

>>> dir("A string or something")

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
"some string {}".format(variable): Here the format method is used to replace the {} with what is inside 'variable'. A callback function can be use in place of 'variable' if it returns something.

class Prompter(object)https://docs.python.org/3/tutorial/class...nheritance

(Mar-29-2017, 03:37 AM)Low_Ki_ Wrote: [ -> ]Another thing... How do I store the username input by the user in a file. Ex:
Just like that. But you have to check if the username isn't in the file already. And you have to decide if the letter case matters.
Format allows you to format your strings for formatted (thus the name) output
I won't be able to explain it's use entirely here, but can give you the basics.

Basic usage:
mood = ['a great',  'a miserable', 'a mundane', 'a happy',  'an exhilarating', 'rather OK'] 
mindex = 4
print('Today is {} day'.format(mood[mindex]))
result:
Output:
Today is an exhilarating day
it can be used for simple variables, and lists also

Please refer to The StringFormatCookbook as a reference when you want to do something more elaborate.
Try some of the examples.
Now I understand. Thank you so much for the explanation guys! It really helps that you explain meanings instead of just writting up the solution and providing it. I very much appreciate the teachings! It's going to take me some time... maybe a couple days to figure out my Login/Registration form but when I do I'll post an update as to what I have so far and respectfully request more constructive criticism.
Also, you can use unpacking with str.format()
>>> l = list(range(1, 11))

>>> s = "{} " * 10

>>> s
'{} {} {} {} {} {} {} {} {} {} '

>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> print(s.format(*l))

1 2 3 4 5 6 7 8 9 10 
(Mar-29-2017, 03:37 AM)Low_Ki_ Wrote: [ -> ]I have not learned about the .format() function yet. Would you please explain.

Learning to program has nothing to do with writing code. The #1 skill you can have for being a decent programmer is learning how to figure things out for yourself, as you'll almost always have something you don't know how to do.

In general, that means using a decent search: http://lmgtfy.com/?q=python+string+format
The very first result is the python docs, with examples of how to use it and why it's useful.

For python, in particular, if you know what something is but not how to use it, you just ask it directly how it wants to be used:
>>> help(''.format)
Help on built-in function format:

format(...) method of builtins.str instance
    S.format(*args, **kwargs) -> str

    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').

>>>
Soooo.... So far this is what I've been able to come up with. I know it's not the most efficient but it does what I need it to for now. I know I will have to end up adding a dictionary for username:password key value pairing and checks.... JSON will probably be my best bet. But as of right now I am proud of my work so here it is. Please comment and critique :D

class Register():

    def __init__(self, prompt_message):
        self.prompt_message = prompt_message

    def user_registration(self):
        prompt_username = input(self.prompt_message)
        filename = 'guest_book.txt'
        if prompt_username.lower() != 'quit':
            with open(filename, 'a+') as file_obj:
                with open(filename, 'r') as file_obj:
                    names = file_obj.readlines()
                    for name in names:
                        if prompt_username.lower() in name.lower():
                            print("Name Taken")
                            break
                    else:
                         with open(filename, 'a') as file_obj:
                            file_obj.write(prompt_username + '\n')
                            print("Welcome to a whole new world, {}".format(prompt_username))


get_username = Register("Please enter the username you wish to create. \n\tOr type 'quit' to exit: ")
get_username.user_registration()
I use the first
with open(filename, 'a+') as file_obj:
in order to create the file incase it doesn't exist. The readlines to create a list to check for existing usernames and the next 'a' to append usernames that do not exist yet.
You open the same file three times, at the same time, all with the same name. Certainly using the same name at the same time is a bad idea, and having them open at the same time makes me nervous. Since you don't need to do it all at once, I would avoid it.
# check to see if the file exists, and create it if necessary
if not os.path.exists(filename):
    with open(filename, 'w') as file_obj:
        pass
# read the names in
with open(filename, 'r') as file_obj:
    name = file_obj.readlines()
for name in names:
    if prompt_username.lower() in name.lower():
        print('Name taken.')
        break
    else:
        # write to the file
        with open(filename, 'a') as file_obj:
            file_obj.write(prompt_username + '\n')
        print('Welcome to a whole new world, {}.'.format(prompt_username))
I took the final print out of the with clause because it doesn't need to be there. I figure, when you're done with the file, be done with the file.

Note that if you use the in operator to check for existing names, and you have the name 'Mary Jane' in the list, you can't create a new user named 'Jane' (because 'Jane' in 'Mary Jane' is True). I'm not sure if that's what you want. If you are trying to avoid the '\n' at the end of the line, I would use:
if prompt_username.lower() == name.strip().lower():
The strip method will return a string with leading and trailing whitespace (including '\n') removed. The returned string goes in the place of name.strip(), and then can then use the lower method.
Pages: 1 2 3