ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

About Python3 -- 2

2022-09-15 18:02:56  阅读:301  来源: 互联网

标签:__ About name -- self def print class Python3


  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,name,--,self,def,print,class,Python3
来源: https://www.cnblogs.com/DocGu/p/16697474.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有