python - OOP实例更新

标签 python oop

我刚刚开始使用 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/

相关文章:

python - 如何从 C++ 返回 Python 类型的实例

python - 根据列对数据帧进行 Argsort

java - Java 重写是如何工作的

java - java中的最大继承级别是多少?

c++ - 好的设计可以完全避免强制转换吗?

php - PHP 构造函数的用途

python - OpenCV 是否具有多目标跟踪功能?

python - 使用Elasticsearch DSL索引数据时出错

java - 使用带有数组的类时遇到问题

python - 如何排序(key=lambda x :) implemented behind the scene?