(Python初学者)需要开始上课吗

2024-05-14 17:12:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始使用类来创建一个简单的联系人输出,然后是这样的更新版本:

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()

我试着看教程和课程文档,但一无所获。任何帮助都将不胜感激,谢谢。你知道吗


Tags: mycontactdirectorymikesmithcontactsprintset
3条回答

如果只想设置属性:

professor.first_name = "Mike"

这将动态添加属性first_name,其值为Mike

如果您需要一个setter,请将其设置为:

class Contact(object):

    def set_first_name(self, fn):
        self._first_name = fn

以及

professor.set_first_name(Mike)

您可能想使用__init__,类构造函数,这使得它更加面向对象:

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装饰器:

类联系人(对象):

@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。这提示outer不应该直接操作这个成员。你知道吗

希望这有帮助。你知道吗

小更新: 我认为在Python中,listContact表示电话簿在大多数情况下已经足够了,包括需要使用ORM/ODM库将其写入数据库的情况。不需要PhoneBook类。只是我的想法。你知道吗

小更新2: 有人在回答和评论中提到__str__,这是一个很好的观点。请看@Bryan Zeng的答案。还有一个叫做__repr__的东西提供了与__str__类似的函数。你知道吗

这个问题可能有帮助:Difference between __str__ and __repr__ in Python

我推荐一本书“Fluent Python”,它在OO一章中介绍了很多“神奇的函数”(以双下线开始和结束的函数),这对Python的OO编程有很大的帮助。你知道吗

小更新3:修复setter/getter decorator上的错误。我有一段时间没用了,我把它写错了。。。@setter应该是@first_name.setter。很抱歉。你知道吗

首先,它需要初始化一个__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
        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

在面向对象编程(OOP)中,类定义具有相关属性的对象。你知道吗

在类中表示联系人的最简单方法是(您猜对了)使用Contact类,但为了保持整洁,我们还将使用Phonebook类:

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()。你知道吗

相关问题 更多 >

    热门问题