Python类实例化的参数 原创

class Test(object):
# class Test: #python中类默认继承object,开发中可以不用写object
	def __init__(self, *args):
		print(args)
		print(*args)


t = Test(1, 2, 3)
## 输出:
	# (1, 2, 3)
	# 1 2 3



class Test1:
	def __init__(self, name, age):
		print(name, age)


t1 = Test1('zhangsan', 20)
## 输出:
	# zhangsan 20
class Test2:
	def __init__(self, name):
		self.name = name
		print('init ' + name)
	
	def __new__(cls, *args, **kwargs):
		print('new')
		cls.__init__(cls, args[0])
		cls.__init__(cls, *args)
		return cls


t2 = Test2('lisi')
## 输出:
	# new
	# init lisi
	# init lisi
	
class Test3:
    def __init__(self, name):
        self.name = name
        print('init')

    def __new__(cls, *args, **kwargs):
        print('new')
        return cls


t3 = Test3('lisi')
## 输出:
	# new

####### 父类(object) __new__ 自动调用__init__,当自定义__new__之后相当于覆盖重写父类的 __new__,这时需要手动调用__init__

posted @ 2024-01-31 11:29  mailfor  阅读(0)  评论(0编辑  收藏  举报  来源