python创建实例必须传入参数吗。

class People(object):
    
    def __init__(self, name):
        self.name = name
    
    def get_name(self):
        return self.name

我在创建实例:
person1 = People()的时候必须传入参数name吗?不然就会报错?

阅读 3.8k
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()

默认参数:

def __init__(self, name=None):
  self.name = name

对于People,是的,因为你的构造函数明确要求需要这个参数

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题