Jump to content
dil_bert

adding new getters and setters in a python code

Recommended Posts

 

dear experts

 

i want  to add to this contact manager a new line of information . the line with the postal adress.

 

in other words ... we have

self.name

self.phne

self.email

 

now i will try to add self.adress -

i do that in exactly the same sheme..

 

 

image.png.1db875c51561e509130469ecb526996f.png

 


 

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	    

 

now i will try to add self.adress -

i do that in exactly the same sheme..

Share this post


Link to post
Share on other sites

 

 

hello dear requinix

 

well the question is - i try to add it like so:

 

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,  theAdress):
14	        self.name = theName
15	        self.phone = thePhone
16	        self.email = theEmail
newnew		self.Adress = theAdress
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
  			def getAdress(self):
19	        return self.adress

24	    # Mutator Methods (setters)
25	    def setPhone(self, newPhoneNumber):
26	        self.phone = newPhoneNumber
27	    def setEmail(self, newEmailAddress):
28	        self.email = newEmailAddress
	    def setAdress(self, newAddress):
	        self.adress = newAddress
29	    def __str__(self):
30	        return "Person[name=" + self.name + \
31	               ",phone=" + self.phone + \
32	               ",email=" + self.email + \
					",email=" + self.email + \
"]"
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: ")
		adress = input("Enter address: ")
39	    return Person(name, phone, email,adress )
40	

 

well i guess that i can do it like so...

 

 

what do you say!'?

love to hear from you

 

greetings

 

 

 

 

Share this post


Link to post
Share on other sites

Besides the indentation problem, which could just be your post, and that you aren't spelling "address" correctly in most of that,

I don't know? Does it work? Is there an error?

Share this post


Link to post
Share on other sites

hello dear requinix

 

many thanks for the quick answer and the hints.

right -the indentation issues are caused by the post (ing)

adress - it is spelled wrong  -

 

but besides this - i will try out the code... i guess that i can do so...

Share this post


Link to post
Share on other sites

good day i got errors - and the  pycharm   ide complained...

#!/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()

in line 36 the last line of this little block..:

 

  return "Person[name=" + self.name + \
               ",phone=" + self.phone + \
               ",email=" + self.email + \
               ",adress=" + self.adress + \
               "]"

 

resolved attribute reference 'adress' for class 'Person' less... (Strg+1)
Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.

what can i do now...

 

anything wrong here .

Edited by dil_bert

Share this post


Link to post
Share on other sites

I don't know Python and it took me only a few seconds to see the problem.

Keep looking.

Share this post


Link to post
Share on other sites

hello dear requinix  ;)

many thanks for the quick reply. i will have a closer look at the code.

Many many thanks for the continued support - this is just great - -

This forum is just a great place to be!

;)

Share this post


Link to post
Share on other sites

hello again

 

after some minor corrections i have the following ..:

 

#!/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()

 

but - i have no option to add more information.

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

 

 

so i need to keep on searching,,,#

 

btw - see the final results.... - there is no option to gather the postal adress:

 

Contacts Manager
1) new contact    2) lookup
3) show all       4) end
> >? 1
Enter friend's name: >? dilbert
Enter phone number: >? 444444444444444444444444444444444444
Enter email address: >? dilbert@hotmail.com
Contacts Manager
1) new contact    2) lookup
3) show all       4) end
> >? 3
Showing all contacts:
Person[name=bernhard schmitt,phone=434345345,email=b.schmitt@hotmail.com]
Person[name=martin ,phone=4444444444444444,email=marle@gmail.com]
Person[name=dilbert,phone=444444444444444444444444444444444444,email=dilbert@hotmail.com]
Contacts Manager
1) new contact    2) lookup
3) show all       4) end

 

 

regards  dil_ bert

 

 

 

Share this post


Link to post
Share on other sites

hello dear Martyr 2


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

Share this post


Link to post
Share on other sites

You must know how to indent your code correctly if you want to use Python. If you are unable to understand indentation then you will have to choose another language to play with.

Share this post


Link to post
Share on other sites

well i have reworked the code

#!/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 = adress
	    def __str__(self):
        return "Person[name={}, phone={}, email={}, adress={}]".format(self.name, self.phone,
                                                                       self.email, self.adress)
# create instance
person = Person(name='John Doe', phone='123454321', email='john.doe@domain.com', adress='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 + \
               ",adress=" + self.adress + \
               "]"
	def enter_a_friend():
    name = input("Enter friend's name: ")
    phone = input("Enter phone number: ")
    email = input("Enter email address: ")
    adress = input("Enter friend's adress:")
    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()


i get back the following

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_six.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_six.py", line 27
    print(person.name)
    ^
IndentationError: unexpected indent

well i still have issues with the IndentationErrors

Share this post


Link to post
Share on other sites

Yeah. Because you still haven't fixed all the indentation problems.

Share this post


Link to post
Share on other sites

hi there - hello requinix

 

first of all many thansk for the continued help _ 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='john.doe@domain.com', 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()

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.