datasci-info / AG101

0 stars 0 forks source link

快速設定self.arg=arg? #1

Closed anniehuang921 closed 9 years ago

anniehuang921 commented 9 years ago

有沒有更快的? 本來是這樣:

class loto(self):
       def __init__(self,x,y,z):
              self.x=x
              self.y=y
              self.z=z

快速設定self.arg=arg?

c3h3 commented 9 years ago

Good Question!

screenshot from 2015-04-01 13 03 55

anniehuang921 commented 9 years ago

限制三個變數,並且用a=A(1,2,3)取代a=A(x=1,y=2,z=3)

class A(object):
    def __init__(self,*args):
        assert len(args) <= 3
        args_names = ["x","y","z"]
        kwargs = dict(zip(args_names[:len(args)],args))
        self.__dict__.update(kwargs)

ps.“一”到三個變數都可以呦~~