Python Forum
Troubleshooting simple script and printing class objects
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Troubleshooting simple script and printing class objects
#11
I wanted to address your recent questions brought to attention in Post 9 && 7, As well as giving you a much better improved version of the input script that populates the instance.

Quote:At line 19, I think I understand the logic of the first half: The method, __str__, returns a line break for each variable inside the template list, while also invoking the join function. Question #1: Is that correct or almost correct?

Almost correct. Lets break it down...

1) The __str__ method returns a string which built in functions such as print() use to obtain a string representation of your object. It basicaly alows you to print objects, that is display a object to the end user.

Check out https://docs.python.org/3/library/stdtypes.html#str

2) template in this case is a list of strings which are joined together with the newline delimiter. Essentialy it builds one long string that looks something like:

"The citizen's first name is {first_name}\nThe citizens'last name is {last_name}"

Check out https://www.programiz.com/python-program...tring/join

3) This long string is then formated , vars(self) returns a dictonary of the variables attached to the object instance. It would look something like:

{'first_name': 'Jon', 'middle_name': 'Ross'}

So you see these are name value pairs, where the names in this case are the variable names, and the values are those of the object instance, in your case citizen256032

Check out https://www.programiz.com/python-program...lt-in/vars

4) What is the ** doing before vars(self)? Well you can pass multiple arguments to functions, sometimes you may write a function that takes multiple arguments but you don't know in advance how many there will be.

In this particular case we can imagine this as breaking up each of the name:value pairs listed above (which are your object variables and their contents)_and passing it to format which can then replace each keyword argument , in this case {first_name} for example with its value (i.e. 'Jon')

so what hapens is
"The citizen's first name is {first_name}\nThe citizens'last name is {last_name}" becomes
"The citizen's first name is Jon\nThe citizens'last name is Dobbs"

Please consider https://www.digitalocean.com/community/t...n-python-3
Read the section titled "Using Formatters with Multiple Placeholders"

What Mekire wrote gives you a way to print a user defined object. Please correct me where I am wrong.

Post 9, Question 4:
Quote: To better flush out what I was trying to ask in Question #4: What if I wanted to invoke a value judgement about some of the information entered by the user. Like for example depending on the iQ entered, the computer will return “You’re super smart!” (if the user inputs an IQ less than 85) or “Dunce!” (if the user’s iQ is above 130)?

How would making a comparison with other information in a database work? For example, how would a program be able to refer to survey results of the citizenry to claim something accurately statistical like: “1 in 182 male Canadians share your same first name (John)”?

you could perform a simple test imediately after gathering the input for example:

person[5] = int(input('What is your IQ?: '))
        while (person[5] not in range(0,160)):
            print('Please enter a number between 0 and 160 inclusive')
            person[5] = int(input('What is your IQ? (0-160): '))

        if person[5] >= 130:
        	print('Dunce!')
However if you are going to go as far as cross referencing the user supplied data with a statistical database you have many things to consider. Is the statistical data a flat file database? In what format is it? There are good books writen on database programming but furthermore
there is SQLite for python https://www.python-course.eu/sql_python.php which you would not have
to reinvent the wheel, as sql as far as i know is standardized and used all over in relational database systems such as mysql. Please correct me where I am wrong.

Lets supose that you have queried this database of first names and found the data "1/128" representing the frequency of your first names popularity. Could be stored as a string or a float maybe?

fnameFrequency = 0.0078

you could write a function that first quierys the data for each peace of triva you are interested in
maybe storing it in a dictionary?

stats = {'Frequency of First Name':0.0078,'some other stat':0.234}
and then test display the results. Probably someone experienced can recomend something more solid.

======================
My revision to the user input routine:
======================

def main():
    # Create new PassPort object instance citizen256032 and populate it with
    # user supplied data from command line.

    EOF = False  # True when end of user input

    while(not EOF):
        fname = getPureString('First Name',3,50,r'[\d]+|[^\w\s]+')
        mname = getPureString('Middle Name (can be blank)',0,50,r'[\d]+|[^\w\s]+').rstrip()
        lname = getPureString('Last Name',3,50,r'[\d]+|[^\w\s]+')
        gender = getPureString('nGender\n\tm) Male\n\tf) Female\nGender',1,1,r'^[^mMfF]$')
        gender = 'Male' if re.match(r'^[mM]$',gender) is not None else 'Female'
        yob = int(getPureString('What year were you born? (yyyy)',4,4,r'[^\d]'))
        iq = int(getPureString('What is your IQ?',1,3,r'[^\d]'))
        EOF = True

    citizen256032 = PassPort(fname,mname,lname,gender,yob,iq)
    print(citizen256032)

# This gets a string from the user that does not contain blacklist characters
# whose length or characer count is within the range supplied via
# minLength and maxLength values.  prompt is the text displayed at the user
# input prompt to give the user an idea what he or she should be entering.
def getPureString(prompt,minLength,maxLength,blacklist):

    while True:
        str = input(prompt + ': ')
        if(re.search(blacklist,str) is None and len(str) in range(minLength,maxLength+1)):
            break
        else:
            print("Error: Invalid input\n")

    return str

 
if __name__ == "__main__":
    main()
Always room for more improvment, also possible might be confusing you with regex if your not versed in using them but this newer code makes me more happy, as my first responce to a user input
routine in my opinion was not great.
Reply
#12
Thank you @knackwurstbagel, for assembling this mighty forum post! You clearly spent hours on this. I am grateful for your care and educational support for Python here on this message board.

@wavic you did a terrific job too.

Thank you both.

I’ll return here soon with some more questions.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Printing out incidence values for Class Object SquderDragon 3 286 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  OBS Script Troubleshooting Jotatochips 0 295 Feb-10-2024, 06:18 PM
Last Post: Jotatochips
  How can I access objects or widgets from one class in another class? Konstantin23 3 1,005 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Troubleshooting with PySpy Positron79 0 806 Jul-24-2022, 03:22 PM
Last Post: Positron79
  Simple Python script, path not defined dubinaone 3 2,695 Nov-06-2021, 07:36 PM
Last Post: snippsat
  Troubleshooting site packages ('h5py' to be specific) aukhare 2 2,000 Nov-02-2020, 03:04 PM
Last Post: snippsat
  Class objects Python_User 12 4,455 Aug-27-2020, 08:02 PM
Last Post: Python_User
  How to create and define in one line a 2D list of class objects in Python T2ioTD 1 2,035 Aug-14-2020, 12:37 PM
Last Post: Yoriz
  OOP hellp (simple class person) onit 4 2,550 Jul-14-2020, 06:54 PM
Last Post: onit
  Need help creating a simple script Nonameface 12 4,547 Jul-14-2020, 02:10 PM
Last Post: BitPythoner

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020