Python教程

About Python3 -- 2

本文主要是介绍About Python3 -- 2,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
  1. class 多态
<1>
class Animal(object):
    def eat(self):
        print("动物会吃")


class Cat(Animal):
    def eat(self):
        print("猫吃鱼")


class Dog(Animal):
    def eat(self):
        print("狗吃骨头")


class Person(object):
    def eat(self):
        print("人吃五谷杂粮")


def func(creature):
    creature.eat()

-- we can override the function of the parent function to create a new class

  1. class methods from the object
<2>
class A(object):
    pass


class B(object):
    pass


class C(A, B):
    def __init__(self, name, age):
        self.name = name
        self.age = age


x = C('gdc', 20)
if __name__ == '__main__':
    # __dict__ 显示 实例 和 方法 的情况
    print(x.__dict__)
    print(C.__dict__)
    print('_____________________________')

    # 输出对象所属的类
    print(x.__class__)
    print(C.__bases__)  # return the tuple of the parent class
    print(C.__base__)  # return the basic parent class
    print(C.__mro__)
    print(A.__subclasses__())  # return the list of the subclasses
    print('_____________________________')

-- 可以使用不同方法得到类的不同信息

  1. special function
<3>
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # override the __add__() can add two classes
    def __add__(self, other):
        return self.age + other.age

    def __len__(self):
        return len(self.name)


stu1 = Student('1', 20)
stu2 = Student('gdc', 20)

if __name__ == '__main__':
    print(stu1 + stu2)
    print('__________________________')
    print(stu2.__len__())

--通过重写add和len方法来实现运算重载的效果

这篇关于About Python3 -- 2的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!