Adding new member variables to python objects?

混江龙づ霸主 提交于 2019-12-05 15:04:11

问题


I have started reading the "Beginning python from novice to professional" by Magnus Lie Hetland, and what struck me today is an ability of an objects to create new member variables, even though those member variables were not present in the class from which the object was "created". Here is an example:

class Test:
    pass

b = Test()

b.variable1 = 12
b.variable2 = "Jim"

print b.variable1
print b.variable2

Until now I though that objects could only change the member values present in parent class, but not create new ones out of thin air? Btw I had no prior knowledge of programming or python.


回答1:


A similar example is given in the Python Docs. According to it, this notation is used for binding together a couple of named items. This is just what Python allows you to do.



来源:https://stackoverflow.com/questions/17043524/adding-new-member-variables-to-python-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!