Python类和类变量的继承

文章目录

基类

代码

class Father:
	name = 'father'
	def __init__(self):
		print("In Father __init__()",self.__class__.name)
		return

	def __new__(cls) -> Any:
		print("In Father __new__()", cls.name)
		return super().__new__(cls)

	def __enter__(self):
		print("In Father __enter__()")
		return "Foo"

	def __exit__(self, type, value, trace):
		print("In Father __exit__()")

	@classmethod
	def Show(cls):
		print("In Father Show()", cls.__name__,cls.name)

class Son(Father):
	#name = 'son'
	def __init__(self) -> None:
		print("In Son __init__()", self.__class__.name)
		super().__init__()

	def __new__(cls) -> Any:
		cls.name = 'son'
		print("In Son __new__()", cls.name)
		return super().__new__(cls)

print('-----------------------')
a = Son.Show()
print('-----------------------')
a = Son().Show()
print('-----------------------')
a = Son.Show()
print('-----------------------')
print(Son.name, Father.name)

执行结果

-----------------------
In Father Show() Son father
-----------------------
In Son __new__() son
In Father __new__() son
In Son __init__() son
In Father __init__() son
In Father Show() Son son
-----------------------
In Father Show() Son son
-----------------------
son father

猜你喜欢

转载自blog.csdn.net/juewuer/article/details/103511436