Python初始化和对象

2024-05-19 11:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个问题。我不知道有没有捷径可以走,但我还是喜欢走捷径。在

假设我有这个班

class a(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "<a(%s', '%s')>" % (self.x, self.y)

    def b(self):
        print('First Name:', self.x, '\nLast Name:', self.y)


user = a('Ade', 'Shola')

假设只有名字

^{pr2}$

我不能用一些“调整”来运行脚本吗?在


Tags: nameselfreturnobjectinitdefclassfirst
2条回答

只需为最后一个参数设置一个空的默认值:

def __init__(self, x, y=None):

您需要在很多逻辑中检查y is None。在

您也可以尝试这样设置任何字段的值…

>>> class a(object):
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

    def __repr__(self):
        return "[a(%s', '%s')]" % (self.x, self.y)

    def b(self):
        print('First Name:', self.x, '\nLast Name:', self.y)

>>> user=a('nsn')
>>> user
[a (nsn', 'None')[
>>> user=a(x='xyx')
>>> user
[a(xyx', 'None')]
>>> user=a(y='abc')
>>> user
[a(None', 'abc')]
>>> 

相关问题 更多 >

    热门问题