我开始使用类来创建简单的联系人输出,然后使用这样的更新版本:
My Contacts
-----------
??? Murphy 555-555-8980
George Smith 555-555-2323
Mike Johnson 555-555-4780
-----------
My Contacts
-----------
Cade Murphy 555-555-8980
President George Smith 555-555-2323
Professor Mike Johnson 555-555-4780
----------
我已正确设置了这些功能,但我不知道要放入class Contact
的内容,以便打印出我想要的内容。
class Contact:
# I don't know what to put here
def print_directory(contacts):
print("My Contacts")
print("-----------")
for person in contacts:
print(person)
print("-----------\n")
def main():
champ = Contact("???", "Murphy", "555-555-8980")
president = Contact("George", "Smith", "555-555-2323")
professor = Contact("Mike", "Johnson", "555-555-4780")
contacts = [champ, president, professor]
print_directory(contacts)
champ.set_first_name("Cade")
president.set_title("President")
professor.set_title("Professor")
print_directory(contacts)
main()
我尝试过关于课程的教程和文档,但是我没有到达任何地方。任何帮助将不胜感激,谢谢。
答案 0 :(得分:3)
如果您只想设置属性:
professor.first_name = "Mike"
这会添加一个属性first_name
,其值为Mike
,动态
如果你需要一个二传手,请多做一次:
class Contact(object):
def set_first_name(self, fn):
self._first_name = fn
和
professor.set_first_name(Mike)
你可能想要使用__init__
这个类构造函数,它使它更加OO:
class Contact(object):
def __init__(self, first_name, last_name, tel):
# convention: private members' name usually start with '_'
self._first_name = first_name
self._last_name = last_name
self._tel = tel
然后你可以使用:
professor = Contact("Mike", "Johnson", "555-555-4780")
如果你想要更多的pythonic OO,你可以使用setter / getter装饰器:
class Contact(object):
@property
def first_name():
# this is a getter
print "getter!"
return self._first_name
@first_name.setter
def first_name(self, first_name):
# this is a setter
print "setter!"
self._first_name = first_name
你可以:
professor = Contact()
professor.first_name = "Mike" # this calls the setter, set value of `_first_name`
print(professor.first_name) # this calls the getter, return value of `_first_name`
注意:Python中的一项约定是将私人成员命名为_
,例如_first_name
。这暗示外部不应直接操作此成员。
希望这有帮助。
小更新:
我认为在Python中,代表电话簿的list
Contact
在大多数情况下都足够了,包括需要使用某些ORM / ODM lib将其写入数据库的情况。不需要PhoneBook
课程。只是我的想法。
小更新2:
有人在回答和评论中说__str__
,这是一个好点。请参阅@Bryan Zeng的回答。还有一个名为__repr__
的东西提供与__str__
类似的功能。
这个问题可能会有所帮助:Difference between __str__ and __repr__ in Python
我推荐了一本书"流利的Python",它引入了很多"魔术功能" (OO章节中的以双下划线开头和结尾的函数),这将为Python OO编程提供很大的帮助。
小更新3:修复setter / getter装饰器上的错误。我暂时没有使用它,我写错了...... @setter
应该是@first_name.setter
。对此抱歉。
答案 1 :(得分:3)
首先,需要进行初始化,以便放置__init__
函数。
class Contact:
def __init__(self, first_name, last_name, phone_number): # Arguments. self is always needed.
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
那么这个类有三个变量。 其次,它需要变成一个字符串。
class Contact:
def __init__(self, first_name, last_name, phone_number): # Arguments. self is always needed.
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
def __str__(self):
return "%s %s \t %s" % (self.first_name, self.last_name, self.phone_number)
您在代码中有一个set_first_name
函数,因此请创建一个
class Contact:
def __init__(self, first_name, last_name, phone_number): # Arguments. self is always needed.
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
def __str__(self):
return "%s %s \t %s" % (self.first_name, self.last_name, self.phone_number)
def set_first_name(self, first_name):
self.first_name = first_name
最后,您的代码中有一个set_title
函数。
class Contact:
def __init__(self, first_name, last_name, phone_number): # Arguments. self is always needed.
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
def __str__(self):
return "%s %s \t %s" % (self.first_name, self.last_name, self.phone_number)
您在代码中有一个set_first_name
函数,因此请创建一个
class Contact:
def __init__(self, first_name, last_name, phone_number): # Arguments. self is always needed.
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
self.title = None
def __str__(self):
if self.title is None:
return "%s %s \t %s" % (self.first_name, self.last_name, self.phone_number)
else:
return "%s %s %s \t %s" % (self.title, self.first_name, self.last_name, self.phone_number)
def set_first_name(self, first_name):
self.first_name = first_name
def set_title(self, title):
self.title = title
答案 2 :(得分:2)
在面向对象编程(OOP)中,类定义了包含相关属性的对象。
在类中表示联系人的最简单方法是(您猜对了)使用Contact类,但为了清洁,我们还会有一个电话簿类:
class Contact:
def __init__(self, first_name, last_name, phone_number):
# The init method is the one called when you instantiate the class
# Ideally it takes all mandatory parameters, that is
# Information without which the object would not fulfill its job
# We could do other stuff, but here we only save the parameters given
# as object properties so you can refer to them later
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
def print_info(self):
# Ideally a data operation class wouldn't be printing anything
# We should return this information as a string and handle it elsewhere
# We'll print it right out of the bat though to keep it straightforward
print(self.first_name, self.last_name, self.phone_number)
class Phonebook:
def __init__(self):
# The phonebooks don't need any special stuff to exist,
# so the only parameter taken is the implicit self
self.contact_list = []
def add(self, contact):
# Here is a method that adds an instance of Contact to the list
self.contact_list.append(contact)
return self
def get_all(self):
# Again, IDEALLY this would be what we would call
# And this list would be handled elsewhere to be printed...
return self.contact_list
def print_all(self):
# ...however this is a small program, and this class can print itself
print("My contacts")
print("-----------")
for contact in self.contact_list:
contact.print_info()
print("-----------\n")
def main():
phonebook = Phonebook() # Phonebook had no __init__, so no params are used
# Then we create the contacts (remember the params we defined at __init__)
champ = Contact("???", "Murphy", "555-555-8980")
president = Contact("George", "Smith", "555-555-2323")
professor = Contact("Mike", "Johnson", "555-555-4780")
# And we add them to the phonebook (remember method add)
# We can chain all .add calls because of the "return self" line
phonebook.add(champ).add(president).add(professor)
# We can then print everything!
phonebook.print_all()
main()
正如已经指出的那样,Python有一个内置的__str__
方法,我们不需要定义print_info()
。我没有改变我的代码块,因为我猜明明解释方法对于初学者来说会更好。不过,更合适的方法是定义__str__
然后print(contact)
而不是调用contact.print_info()
。