佚名通过本文主要向大家介绍了python脚本编写实例,python项目实例,python开发网站实例,python创建类的实例,python程序实例等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
问题:python创建实例必须传入参数吗。
描述:
解决方案1:
描述:
class People(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
我在创建实例:
person1 = People()的时候必须传入参数name吗?不然就会报错?
解决方案1:
对于People,是的,因为你的构造函数明确要求需要这个参数
解决方案2:默认参数:
def __init__(self, name=None):
self.name = name
解决方案3:python支持可变参数的写法,你需要调整下构造函数的原型
class People(object):
def __init__(self, *args):
self.args = args
def sayAge(self):
print str(self.args)
p1 = People()
p2 = People('charlie')
p3 = People('charlie', 22)
p1.sayAge()
p2.sayAge()
p3.sayAge()