美文网首页Python
Python轻松入门 - 5 类的定义和使用

Python轻松入门 - 5 类的定义和使用

作者: V哥带你写程序 | 来源:发表于2019-05-16 18:17 被阅读0次

    类的定义:把成员变量及其操作方法封装在一起就叫类

    python类的定义,class关键字加冒号

    class Casher:
        def __init__(self, initAmount: int = 0):
            self.total = initAmount
    
        def receiveMoney(self, goodPrice: int):
            self.total += goodPrice
    
        def __repr__(self) -> str:
            return str(self.total)
    

    类方法

    • 面向对象编程有继承的概念,所有类的Parent都是Object, Object有默认方法,这些方法名都是两个下划线方法名两个下划线的形式,常用的方法有: 两个下划线init两个下划线是constructor, 两个下划线repr两个下划线 represent方法类似于Java中的toString()方法
    • 类方法定义中的第一个参数必须是self

    使用类

    从类创建对象

    c = Casher(100)
    c.receiveMoney(50)
    print(c)
    c.total
    
    d = Casher()
    d.receiveMoney(20)
    print(d)
    

    检查一个对象的类型

    type(d)

    相关文章

      网友评论

        本文标题:Python轻松入门 - 5 类的定义和使用

        本文链接:https://www.haomeiwen.com/subject/jnhwaqtx.html