类的专有方法

Python文档——类

类的专有方法

  • __init__ : 构造函数,在生成对象时调用
    -__del__: 析构函数,释放对象时使用
  • __repr__: 打印,转换
  • __setitem__: 按照索引赋值
  • __getitem__: 按照索引获取值
  • __len__: 获得长度
  • __cmp__: 比较运算
  • __call__: 函数调用
  • __add__: 加运算
  • __sub__: 减运算
  • __mul__: 乘运算
  • __truediv__: 除运算
  • __mod__: 求余运算
  • __pow__: 乘方
  • __str__:调用print()打印实例化对象时会调用__str__(),打印其中的返回值。

运算符重载

__str____add__演示:

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector ({}, {})'.format(self.a, self.b)

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)


v1 = Vector(2, 10)
v2 = Vector(-5, 20)
print(v1 + v2)  # Vector (-3, 30)

不相关的例子:

class People:
    name = ''
    age = 0
    __weight = 0

    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def say(self):
        print('My name is {}, I\'m {}.'.format(self.name, self.age))


class Student(People):
    grade = ''

    def __init__(self, n, a, w, g):
        People.__init__(self, n, a, w)
        self.grade = g

    def __str__(self):
        return 'name: {}\nage: {}'.format(self.name, self.age)


stu = Student('Zhang', 20, 'daer', 120)
print(stu) 
# name: Zhang
#age: 20
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容