Python中类的理解

在这里插入图片描述

继承

class firstClass:
    def setdata(self, value):
        self.data = value
    def display(self):
        print(self.data)

x = firstClass()
y = firstClass()
x.setdata('aaa')
y.setdata(21)
x.display()
# output: aaa
y.display()
# output:21
x.data = 'hehe'
x.display()
output: hehe

x,y本身没有setdata属性,Python会顺着类的连接搜索,也就是Python的继承,继承在属性点号运算时发生的,只于查找连接对象内的变量名有关。以上代码例子中的x.setdata(‘aaa’)会传入self.data中。因为类会产生多个实例,所以必须经过self参数才能获取正在处理的实例。
在这里插入图片描述

重载

class SecondClass(firstClass):
    def display(self):
        print('Current value = "%s"' % self.data)

z = SecondClass()
z.setdata(43)
z.display()
# output: Current value = "43"

因为SecondClass中的变量display在firstClass中找到,所以SecondClass覆盖了firstClass中的变量display,将这种在书中较低处发生的重新定义取代属性的行为成为重载。
在这里插入图片描述
在这里插入图片描述

构造函数方法(init

class ThirdClass(SecondClass):
    def __init__(self, value):
        self.data = value
    def __add__(self, other):
        return ThirdClass(self.data + other)
    def __str__(self):
        return '[ThirdClass: %s]' % self.data
    def mul(self, other):
        self.data *= other

a = ThirdClass('abc')
a.display()
print(a)
# output:Current value = "abc"
#  			[ThirdClass: abc]

b = a + 'xyz'
b.display()
print(b)
# output:Current value = "abcxyz"
#  			[ThirdClass: abcxyz]

a.mul(3)
print(a)
# output:[ThirdClass: abcabcabc]

在这里插入图片描述
ThirdClass会继承SecondClass的display方法。ThirdClass在生成调用时会传递一个参数,这是传给__init__构造函数内参数value的,并赋值给self.data。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值