开发者

Python init and Objects

I have this issue. I wouldn't know if there is any short-cut to it but I would love a short-cut though.

Say I have this class

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')

Assuming there is only the first name,

user = a('Ade')

Can't I still run the sc开发者_如何学JAVAript with some 'tweaks'?


Just set a null default value for the last parameter:

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

You'll need to check for y is None in a lot of your logic.


You can also try this so set value of any field that you want...

>>> 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')]
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜