Python内置方法与面向对象知识点进阶系列 常见的类的内置方法

Python中的魔法方法(双下划线方法)

常见的内置方法汇总

常见的类的内置方法 ***

使用__getitem__与__len__实现一个可迭代/可计算长度的对象

class Company(object):
    #魔法函数
    def __init__(self, employee_list):
        self.employee = employee_list

    def __getitem__(self, item):
        return self.employee[item]
    # 不写它只有__getitem__的话还是能使用len求出长度的
    def __len__(self):
        return len(self.employee)


company = Company(["tom", "whw", "jane"])
#
# for i in company.employee:
#     print(i)

company1 = company[:2]
# 调用__len__方法
print(len(company)) # 3
# 调用__getitem__方法
for em in company1:
    print(em)
"""
tom
whw
"""

super方法

# 使用super函数
# 当前的类和对象可以作为super函数的参数使用,调用返回的对象的任何方法都是
# super函数会自动寻找他所需要的特性,直到返回一个AttributeError异常
class Bird:
    def __init__(self):
        self.hungry=True
    def eat(self):
        if self.hungry:
            print("eat")
            self.hungry=False
        else:
            print("no")

class SongBird(Bird):
    def __init__(self):
        super(SongBird,self).__init__()
        self.sound="lalala"

    def sing(self):
        print(self.sound)

sb=SongBird()
sb.sing() # lalala
sb.eat() # eat
sb.eat() # no

123

123

123

123

123

猜你喜欢

转载自www.cnblogs.com/paulwhw/p/12940991.html