python

算术运算符

类型工厂函数,指的是“不通过类而是通过函数来创建对象”。

【例子】

1

class C:

2

    pass

3

4

5

print(type(len))  # <class 'builtin_function_or_method'>

6

print(type(dir))  # <class 'builtin_function_or_method'>

7

print(type(int))  # <class 'type'>

8

print(type(list))  # <class 'type'>

9

print(type(tuple))  # <class 'type'>

10

print(type(C))  # <class 'type'>

11

print(int('123'))  # 123

12

13

# 这个例子中list工厂函数把一个元祖对象加工成了一个列表对象。

14

print(list((1, 2, 3)))  # [1, 2, 3]
<class 'builtin_function_or_method'>

<class 'builtin_function_or_method'>

<class 'type'>

<class 'type'>

<class 'type'>

<class 'type'>

123

[1, 2, 3]
  • __add__(self, other)定义加法的行为:+
  • __sub__(self, other)定义减法的行为:-

【例子】

1

class MyClass:

2

3

    def __init__(self, height, weight):

4

        self.height = height

5

        self.weight = weight

6

7

    # 两个对象的长相加,宽不变.返回一个新的类

8

    def __add__(self, others):

9

        return MyClass(self.height + others.height, self.weight + others.weight)

10

11

    # 两个对象的宽相减,长不变.返回一个新的类

12

    def __sub__(self, others):

13

        return MyClass(self.height - others.height, self.weight - others.weight)

14

15

    # 说一下自己的参数

16

    def intro(self):

17

        print("高为", self.height, " 重为", self.weight)

18

19

20

def main():

21

    a = MyClass(height=10, weight=5)

22

    a.intro()

23

24

    b = MyClass(height=20, weight=10)

25

    b.intro()

26

27

    c = b - a

28

    c.intro()

29

30

    d = a + b

31

    d.intro()

32

33

34

if __name__ == '__main__':

35

    main()

36

37

# 高为 10  重为 5

38

# 高为 20  重为 10

 

39

# 高为 10  重为 5

40

# 高为 30  重为 15
高为 10  重为 5

高为 20  重为 10

高为 10  重为 5

高为 30  重为 15
  • __mul__(self, other)定义乘法的行为:*
  • __truediv__(self, other)定义真除法的行为:/
  • __floordiv__(self, other)定义整数除法的行为://
  • __mod__(self, other) 定义取模算法的行为:%
  • __divmod__(self, other)定义当被 divmod() 调用时的行为
  • divmod(a, b)把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值