Python的数据类型

  • 列表(list)、字典(dict)、集合(set)、文件(file)、字符串(str),这些都是对象

扩展list的功能,详解如图:

Python面向对象——内置对象的功能扩展

我们给列表添加了新的功能,搜索功能,能够找出给定字符串是否在列表中,如果在列表中,就返回列表中的字符串。图解如下 :
Python面向对象——内置对象的功能扩展

 扩展dict的功能,详解如图:

Python面向对象——内置对象的功能扩展

Python面向对象——内置对象的功能扩展

2.代码验证

class ContactList(list):
    def search(self, name):
        matching_contacts = []
        for contact in self:
            if name in contact.name:
                matching_contacts.append(contact)
        return matching_contacts

class Contact:
    all_contacts = ContactList()
    def __init__(self, name, email):
        self.name = name 
        self.email = email
        self.all_contacts.append(self)
        
c1 = Contact("john aa", "y@.net")
c2 = Contact("john bb", "b@.net")
c3 = Contact("john bb", "c@.net")

[c.name for c in  Contact.all_contacts.search("john")]
class LongNameDict(dict):
    def longest_key(self):
        longest = None
        for key in self:
            if not longest or len(key) > len(longest):
                longest = key
        return longest

longkeys = LongNameDict()
longkeys['AAA'] = 1
longkeys['BBBB'] = 12
longkeys['CCCCC'] = 'nihao'

longkeys.longest_key()

参考:本文参考学习《Python3 Object Oriented Programming》,Dusty Phillips 著

相关文章:

  • 2022-12-23
  • 2022-02-16
  • 2021-09-24
  • 2021-08-08
  • 2021-07-16
  • 2022-12-23
猜你喜欢
  • 2021-09-07
  • 2022-12-23
  • 2021-12-27
  • 2021-05-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
相关资源
相似解决方案