我刚刚开始使用 OOP,我对这段代码感到困惑 -
class cartesianPoint:
pass
cp1 = cartesianPoint()
cp1.x = 1.0
cp1.y = 2.0
cp1
>
<__main__.cartesianPoint instance at 0x0000000001E7EB88>
首先,为什么我可以向不属于类的对象添加新变量?如果类是对象的蓝图,那么对象不应该遵循蓝图吗?即使 python 允许你这样做,为什么对象仍然属于同一个类?
最佳答案
查看第 9.4 节:http://docs.python.org/2/tutorial/classes.html
Note that clients may add data attributes of their own to an instance object without affecting the validity of the methods, as long as name conflicts are avoided
cp1 确实是 CartesianPoint 类的实例,但您已向该特定实例添加了 2 个新数据成员,这对该类本身或任何后续实例没有影响.
请记住,CartesianPoint 类的每个实例都有自己的字段和方法字典。
关于python - OOP实例更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395002/