Python 面向对象 —— super 的使用(Python 2.x vs Python 3.x)

36 篇文章 3 订阅

注意区分当前的 Python 版本是 2.X 还是 3.X,Python 3.X 在 super 的使用上较之 Python 2.X 有较大的变化;

0. super 的使用

  • 使用 super 关键字调用父类:

    # 如果不使用 super
    class A:
      def __init__(self):
       print("enter A")
       print("leave A")
    
     class B(A):
      def __init__(self):
       print("enter B")
       A.__init__(self)
       print("leave B")
    
    # 此时如果将 B 继承自 C
     class B(A):
      def __init__(self):
       print("enter B")
       C.__init__(self)
       print("leave B")
    

    使用 super 关键字,则不必关注其继承的是哪个父类:

    class B(A):
    	def __init__(self):
    		print("enter B")
    		super(B, self).__init__()
    		print("leave B") 
    

1. Python 2.x

class Contact(object):
	all_contacts = []
	def __init__(self, name, email):
		self.name = name
		self.email = email
		Contact.all_contacts.append(self)

class Friend(Contact):
	def __init__(self, name, email, phone):
		super(Friend, self).__init__(name, email)
		self.phone = phone

Python 2.x 的环境下,对于需要被继承的父类,需要显式地将父类继承自 object 类,否则在子类使用 super(子类, self).__init__() 时会报 TypeError: must be type, not classobj.

这是因为 Python 2.x 中:

>> class A():
	   pass
>> type(A)
classobj

>> class A(object):
	   pass
>> type(A)
type

而且 Python 2.x 也并不将 classobj 视为 type.

当然子类中使用这样的语句也是可以的:

class Friend(Contact):
	def __init__(self, name, email, phone):
		Contact.__init__(self, name, email, phone)
		self.phone = phone

<a href=“http://zhidao.baidu.com/link?url=uPkcvhMb4Cp4ddupz3xpswGQSkxoXpxqhZ58cB4tiITgHRQJXRpxkWejjNE5KYHtFuAVgArdPwzjZPDc5yYMsCZqcj8bNnzmIbROrhaON6O”, target="_blank">python super()用法遇到TypeError: must be type, not classobj

2. Python 3.x

class Contact:
	all_contacts = []
	def __init__(self, name, email):
		self.name = name
		self.email = email
		Contact.all_contacts.append(self)

class Friend(Contact):
	def __init__(self, name, email, phone):
		super().__init__(name, email)
		self.phone = phone
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值