Python Forum

Full Version: rework of a little python-script - extending getters and setters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello dear all,

fairly new to python

with this little script i am trying to learn some steps reagarding oo programming.

i want to extend this little script to gather some more information:


01	#!/usr/bin/env python3
02	"""
03	contacts.py
04	This program uses a Person class to keep track of contacts.
05	"""
06	
07	class Person(object):
08	    """
09	    The Person class defines a person in terms of a
10	    name, phone number, and email address.
11	    """
12	    # Constructor
13	    def __init__(self, theName, thePhone, theEmail):
14	        self.name = theName
15	        self.phone = thePhone
16	        self.email = theEmail
17	    # Accesser Methods (getters)
18	    def getName(self):
19	        return self.name
20	    def getPhone(self):
21	        return self.phone
22	    def getEmail(self):
23	        return self.email
24	    # Mutator Methods (setters)
25	    def setPhone(self, newPhoneNumber):
26	        self.phone = newPhoneNumber
27	    def setEmail(self, newEmailAddress):
28	        self.email = newEmailAddress
29	    def __str__(self):
30	        return "Person[name=" + self.name + \
31	               ",phone=" + self.phone + \
32	               ",email=" + self.email + \
33	               "]"
34	
35	def enter_a_friend():
36	    name = input("Enter friend's name: ")
37	    phone = input("Enter phone number: ")
38	    email = input("Enter email address: ")
39	    return Person(name, phone, email)
40	
41	def lookup_a_friend(friends):
42	    found = False
43	    name = input("Enter name to lookup: ")
44	    for friend in friends:
45	        if name in friend.getName():
46	            print(friend)
47	            found = True
48	    if not found:
49	        print("No friends match that term")
50	
51	def show_all_friends(friends):
52	    print("Showing all contacts:")
53	    for friend in friends:
54	        print(friend)
55	
56	def main():
57	    friends = []
58	    running = True
59	    while running:
60	        print("\nContacts Manager")
61	        print("1) new contact    2) lookup")
62	        print("3) show all       4) end ")
63	        option = input("> ")
64	        if option == "1":
65	            friends.append(enter_a_friend())
66	        elif option == "2":
67	            lookup_a_friend(friends)
68	        elif option == "3":
69	            show_all_friends(friends)
70	        elif option == "4":
71	            running = False
72	        else:
73	            print("Unrecognized input. Please try again.")
74	    print("Program ending.")
75	
76	if __name__ == "__main__":
77	    main()
78	
79	
what is wanted... to gather information regarding

    # Constructor

    def __init__(self, theName, thePhone, theEmail, theAdress, ):
        self.name = theName
        self.phone = thePhone
        self.email = theEmail
        self.Adress = theAdress
 
but untill now i have no luck... i only am able to gather inforamtion about the following aspects

    # Constructor
    def __init__(self, theName, thePhone, theEmail, theAdress, ?
        self.name = theName
        self.phone = thePhone
        self.email = theEmail
and the newly added adress - it does not get in effect..

        self.Adress = theAdress
- see my approach:

#!/usr/bin/env python3
"""
contacts.py
This program uses a Person class to keep track of contacts.
@author Richard White
@version 2016-07-30
"""

class Person(object):
    """
    The Person class defines a person in terms of a
    name, phone number, and email address.
    """
    # Constructor
    def __init__(self, theName, thePhone, theEmail, theAdress, ):
        self.name = theName 
        self.phone = thePhone
        self.email = theEmail
        self.adress = theAdress
    # Accesser Methods (getters)
    def getName(self):
        return self.name
    def getPhone(self):
        return self.phone
    def getEmail(self):
        return self.email
    def getAdress(self):
        return self.adress;
    # Mutator Methods (setters)
    def setPhone(self, newPhoneNumber):
        self.phone = newPhoneNumber
    def setEmail(self, newEmailAddress):
        self.email = newEmailAddress
    def __str__(self):
        return "Person[name=" + self.name + \
               ",phone=" + self.phone + \
               ",email=" + self.email + \
               ",adress=" + self.adress + \
               "]"

def enter_a_friend():
    name = input("Enter friend's name: ")
    phone = input("Enter phone number: ")
    email = input("Enter email address: ")
    return Person(name, phone, email)

def lookup_a_friend(friends):
    found = False
    name = input("Enter name to lookup: ")
    for friend in friends:
        if name in friend.getName():
            print(friend)
            found = True
    if not found:
        print("No friends match that term")

def show_all_friends(friends):
    print("Showing all contacts:")
    for friend in friends:
        print(friend)

def main():
    friends = []
    running = True
    while running:
        print("\nContacts Manager")
        print("1) new contact    2) lookup")
        print("3) show all       4) end ")
        option = input("> ")
        if option == "1":
            friends.append(enter_a_friend())
        elif option == "2":
            lookup_a_friend(friends)
        elif option == "3":
            show_all_friends(friends)
        elif option == "4":
            running = False
        else:
            print("Unrecognized input. Please try again.")
    print("Program ending.")

if __name__ == "__main__":
    main()
well - i guess that i have to look and i have to try to find out what goes wrong...
Again:


what is wanted... to gather information regarding

    # Constructor

    def __init__(self, theName, thePhone, theEmail, theAdress, ):
        self.name = theName
        self.phone = thePhone
        self.email = theEmail
        self.Adress = theAdress
 
but untill now i have no luck... i only am able to gather inforamtion about the following aspects

    # Constructor
    def __init__(self, theName, thePhone, theEmail, theAdress, ?
        self.name = theName
        self.phone = thePhone
        self.email = theEmail
and the newly added adress - it does not get in effect..

        self.Adress = theAdress
love to hear from you
This is Python, not Java. You never almost never use getters and setters in Python. If you really need that sort of security you use properties. But a class like the one in your example, you just don't bother.
hello dear Ichablod


first of all - many thanks for the hints!!


still run into some issues ...


#!/usr/bin/env python3
"""
contacts.py
This program uses a Person class to keep track of contacts.
@author Richard White
@version 2016-07-30
"""

class Person(object):
    """
    The Person class defines a person in terms of a
    name, phone number, and email address.
    """
    # Constructor
    def __init__(self, theName, thePhone, theEmail, theAdress):
        self.name = theName
        self.phone = thePhone
        self.email = theEmail
        self.adress = theAdress
    # Accesser Methods (getters)
    def getName(self):
        return self.name
    def getPhone(self):
        return self.phone
    def getEmail(self):
        return self.email
    # Mutator Methods (setters)
    def setPhone(self, newPhoneNumber):
        self.phone = newPhoneNumber
    def setEmail(self, newEmailAddress):
        self.email = newEmailAddress
    def __str__(self):
        return "Person[name=" + self.name + \
               ",phone=" + self.phone + \
               ",email=" + self.email + \
               ",adress=" + self.adress + \
               "]"

def enter_a_friend():
    name = input("Enter friend's name: ")
    phone = input("Enter phone number: ")
    email = input("Enter email address: ")
    address = input("Enter friend's address:")
    return Person(name, phone, email)

def lookup_a_friend(friends):
    found = False
    name = input("Enter name to lookup: ")
    for friend in friends:
        if name in friend.getName():
            print(friend)
            found = True
    if not found:
        print("No friends match that term")

def show_all_friends(friends):
    print("Showing all contacts:")
    for friend in friends:
        print(friend)

def main():
    friends = []
      running = True
    while running:
        print("\nContacts Manager")
        print("1) new contact    2) lookup")
        print("3) show all       4) end ")
        option = input("> ")
        if option == "1":
            friends.append(enter_a_friend())
        elif option == "2":
            lookup_a_friend(friends)
        elif option == "3":
            show_all_friends(friends)
        elif option == "4":
            running = False
        else:
            print("Unrecognized input. Please try again.")
    print("Program ending.")

if __name__ == "__main__":
    main()
see what i get back
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
runfile('C:/_safings_/_dev_/python/contacts__backup_zwei.py', wdir='C:/_safings_/_dev_/python')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/_safings_/_dev_/python/contacts__backup_zwei.py", line 63
    running = True
    ^
IndentationError: unexpected indent
Obviously indentation of line 63 is off. Fix it so that it is aligned with the line above. However you are not listening to what @ichabod801 tells you. Your class should look like this

class Person(object):
    """
    The Person class defines a person in terms of a
    name, phone number, and email address.
    """
    # Constructor
    def __init__(self, name, phone, email, address):
        self.name = name
        self.phone = phone
        self.email = email
        self.adress = address

    def __str__(self):
        return "Person[name={}, phone={}, email={}, address={}]".format(self.name, self.phone,
                                                                        self.email, self.adress)

# create instance
person = Person(name='John Doe', phone='123454321', email='[email protected]',
                address='1600 Pennsylvania ave., Washington DC')
#access property
print(person.name)

#print object
print(person)

# assign new value of property
person.name = 'Jack Ryan'

# print again
print(person)
Output:
John Doe Person[name=John Doe, phone=123454321, [email protected], address=1600 Pennsylvania ave., Washington DC] Person[name=Jack Ryan, phone=123454321, [email protected], address=1600 Pennsylvania ave., Washington DC]
hi there buran

i fixed the indent issue and changed the class - but there were new issues arising

#!/usr/bin/env python3
"""
contacts.py
This program uses a Person class to keep track of contacts.
@author Richard White
@version 2016-07-30
"""


class Person(object):
    """
    The Person class defines a person in terms of a
    name, phone number, and email address.
    """

    # Constructor
    def __init__(self, name, phone, email, address):
        self.name = name
        self.phone = phone
        self.email = email
        self.adress = address

    def __str__(self):
        return "Person[name={}, phone={}, email={}, address={}]".format(self.name, self.phone,
                                                                        self.email, self.adress)


# create instance
person = Person(name='John Doe', phone='123454321', email='[email protected]',
                address='1600 Pennsylvania ave., Washington DC')
# access property
print(person.name)

# print object
print(person)

# assign new value of property
person.name = 'Jack Ryan'

# print again
print(person)
    # Accesser Methods (getters)
    def getName(self):
        return self.name
    def getPhone(self):
        return self.phone
    def getEmail(self):
        return self.email
    # Mutator Methods (setters)
    def setPhone(self, newPhoneNumber):
        self.phone = newPhoneNumber
    def setEmail(self, newEmailAddress):
        self.email = newEmailAddress
    def __str__(self):
        return "Person[name=" + self.name + \
               ",phone=" + self.phone + \
               ",email=" + self.email + \
               "]"

def enter_a_friend():
    name = input("Enter friend's name: ")
    phone = input("Enter phone number: ")
    email = input("Enter email address: ")
    return Person(name, phone, email)

def lookup_a_friend(friends):
    found = False
    name = input("Enter name to lookup: ")
    for friend in friends:
        if name in friend.getName():
            print(friend)
            found = True
    if not found:
        print("No friends match that term")

def show_all_friends(friends):
    print("Showing all contacts:")
    for friend in friends:
        print(friend)

def main():
    friends = []
    running = True
    while running:
        print("\nContacts Manager")
        print("1) new contact    2) lookup")
        print("3) show all       4) end ")
        option = input("> ")
        if option == "1":
            friends.append(enter_a_friend())
        elif option == "2":
            lookup_a_friend(friends)
        elif option == "3":
            show_all_friends(friends)
        elif option == "4":
            running = False
        else:
            print("Unrecognized input. Please try again.")
    print("Program ending.")

if __name__ == "__main__":
    main()
the new issues look like so

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
runfile('C:/_safings_/_dev_/python/contacts__100.py', wdir='C:/_safings_/_dev_/python')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/_safings_/_dev_/python/contacts__100.py", line 43
    def getName(self):
    ^
IndentationError: unexpected indent
i will have a closer look
lines 42-59 are leftover from your initial code. you need to remove them. And to be honest this is something you should be able t see just from reading the traceback and looking at respective code.
And after resolve this particular error there are multiple issues with the rest of the code:
  • enter_a_friend() function does not ask for address, so you will get error because Person.__init__() expects you to pass 4 arguments (5 with self)
  • on line 70 you still try to access name using getName()
hello Buran

thx for the answer - finally got there

#!/usr/bin/env python3
"""
contacts.py
This program uses a Person class to keep track of contacts.
"""
class Person(object):
    """
    The Person class defines a person in terms of a
    name, phone number, and email address.
    """

    # Constructor
    def __init__(self, name, phone, email, padress):
        self.name = name
        self.phone = phone
        self.email = email
        self.padress = padress

    def __str__(self):
        return "Person[name={}, phone={}, email={}, padress={}]".format(self.name, self.phone,
                                                                       self.email, self.padress)
# create instance person = Person(name='John Doe', phone='123454321', email='[email protected]', adress='1600 Pennsylvania ave., Washington DC')
# access property
    # Accesser Methods (getters)
    def getName(self):
        return self.name
    def getPhone(self):
        return self.phone
    def getEmail(self):
        return self.email
    def getpadress(self):
        return self.padress
  
 # Mutator Methods (setters)
    def setPhone(self, newPhoneNumber):
        self.phone = newPhoneNumber
    def setEmail(self, newEmailAddress):
        self.email = newEmailAddress
    def setPadress(self, newPadress):
        self.padress = newPadress
    def __str__(self):
        return "Person[name=" + self.name + \
               ",phone=" + self.phone + \
               ",email=" + self.email + \
               ",padress=" + self.padress + \
               "]"

def enter_a_friend():
    name = input("Enter friend's name: ")
    phone = input("Enter phone number: ")
    email = input("Enter email address: ")
    padress = input("Enter friend's padress:")
    return Person(name, phone, email, padress)

def lookup_a_friend(friends):
    found = False
    name = input("Enter name to lookup: ")
    for friend in friends:
        if name in friend.getName():
            print(friend)
            found = True
    if not found:
        print("No friends match that term")

def show_all_friends(friends):
    print("Showing all contacts:")
    for friend in friends:
        print(friend)

def main():
    friends = []
    running = True
    while running:
        print("\nContacts Manager")
        print("1) new contact    2) lookup")
        print("3) show all       4) end ")
        option = input("> ")
        if option == "1":
            friends.append(enter_a_friend())
        elif option == "2":
            lookup_a_friend(friends)
        elif option == "3":
            show_all_friends(friends)
        elif option == "4":
            running = False
        else:
            print("Unrecognized input. Please try again.")
    print("Program ending.")

if __name__ == "__main__":
    main()
next step is to add db connection to a mysql-db...

i will dig into the possible options here. - Probably i can use peewee here.
(Nov-04-2018, 11:51 AM)apollo Wrote: [ -> ]thx for the answer - finally got there
You still don't lissen to advice about getters and setters.
If i delete(getters/setters) and do some PEP-8 fixes,30 lines are gone Angel
"""
contacts.py
This program uses a Person class to keep track of contacts.
"""
class Person(object):
    """
    The Person class defines a person in terms of a
    name, phone number, and email address.
    """
    def __init__(self, name, phone, email, padress):
        self.name = name
        self.phone = phone
        self.email = email
        self.padress = padress

    def __str__(self):
        return "Person[name={}, phone={}, email={}, address={}]".format(
            self.name, self.phone, self.email, self.padress
        )

def enter_a_friend():
    name = input("Enter friend's name: ")
    phone = input("Enter phone number: ")
    email = input("Enter email address: ")
    padress = input("Enter friend's padress:")
    return Person(name, phone, email, padress)

def lookup_a_friend(friends):
    found = False
    name = input("Enter name to lookup: ")
    for friend in friends:
        if name in friend.name:
            print(friend)
            found = True
    if not found:
        print("No friends match that term")

def show_all_friends(friends):
    print("Showing all contacts:")
    for friend in friends:
        print(friend)

def main():
    friends = []
    running = True
    while running:
        print("\nContacts Manager")
        print("1) new contact    2) lookup")
        print("3) show all       4) end ")
        option = input("> ")
        if option == "1":
            friends.append(enter_a_friend())
        elif option == "2":
            lookup_a_friend(friends)
        elif option == "3":
            show_all_friends(friends)
        elif option == "4":
            running = False
        else:
            print("Unrecognized input. Please try again.")
    print("Program ending.")

if __name__ == "__main__":
    main()
Python Is Not Java
Quote:Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans.
Do not write getters and setters.
This is what the 'property' built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in 'property'.
That means that until you prove that you need anything more than a simple attribute access, don't write getters and setters.
They are a waste of CPU time, but more important, they are a waste of programmer time.
Not just for the people writing the code and tests, but for the people who have to read and understand them as well.