Why can't I directly add attributes to any python object?

前端 未结 3 1714
情歌与酒
情歌与酒 2020-12-09 16:56

I have this code:

>>> class G:
...   def __init__(self):
...     self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000         


        
3条回答
  •  醉酒成梦
    2020-12-09 16:59

    While the question has already been answered; if anyone is interested in a workaround, here's an example --

    mydate = datetime.date(2013, 3, 26)
    mydate.special = 'Some special date annotation'  # doesn't work
    ...
    class CustomDate(datetime.date):
        pass
    mydate = datetime.date(2013, 3, 26)
    mydate = CustomDate(mydate.year, mydate.month, mydate.day)
    mydate.special = 'Some special date annotation'  # works
    

提交回复
热议问题