【问题标题】:Python OOP - Are attributes objects within objects?Python OOP - 对象内的属性对象吗?
【发布时间】:2015-10-11 15:13:46
【问题描述】:

我有一些关于类和一般 OOP 的问题。

# Lets say we have this variable.
my_integer = 15

现在,如果我做对了,当分配发生时,Python 会创建一个值为 15 的 int 类对象,然后由定义为 my_integer 的名称标签引用。 p>

# Now we "change" it.
my_integer = 50

现在应该创建一个值为 50 的新 int 对象,但引用标记切换到新创建的对象,从而使具有 15 的对象没有标记并用于垃圾处理。

class Point:
        """Point class represents and manipulates x,y coords."""

        def __init__(self):
        self.x = 0
        self.y = 0

one = Point()
two = Point()

one.x = 50
two.y = 150

当我创建具有 x 和 y 属性的 Point() 对象时,Python 基本上是在 Point() 对象内创建一个整数对象吗?

如果一个对象里面有多个对象,是不是有点复杂?

我对前两点的理解正确吗?

【问题讨论】:

  • 在内部,像整数这样的原始值通常由语言实现专门处理,因为它们太多了,每次对它们执行操作时分配和释放整数会花费太多时间。
  • 有一个很好的讨论:youtube.com/watch?v=_AEJHKGk9ns
  • @sobolevn 已经知道那个谈话 XD。澄清了很多误解,但我问前两个只是为了确认,它并没有真正谈论内部类型是如何处理的。
  • 如果我错了,请纠正我,但新对象不是在 Point 对象“内部”创建的。它是从一个堆中分配的(如果没有从另一个堆中重用),并且它的地址被标记在位于 Point 对象的命名空间中的名称中。

标签: python class oop variables


【解决方案1】:

基本上是的。让我们更仔细地看一下:

class Point:
        """Point class represents and manipulates x,y coords."""

        def __init__(self):
        self.x = 0 # Create an int-object and set self.x to that
        self.y = 0 # Same as above

one = Point()
# Create a general object tag (Point extends object) by calling
# Point.__init__(Point.__new__()) *see more below
two = Point()
# The same
one.x = 50 # Create an int-object and assign it
two.y = 150

实例创建

类的实例创建比上面看起来更特别。每个类实际上都有一个meta-class ,它是类的类型。这最终解决了 - 可能在几层嵌套之后 - 内置类 type

当实例化发生时(如您的代码Point()),会发生以下情况:

a = Class(*args, **wargs) # Class is some class you defined
# calls type(Class).__call__(Class, *args, **wargs)
# normally type(Class) is type, and type.__call__() does the following
# def type.__call__(clz, *args, **wargs): # Not a perfect implementation
#      protoobj = clz.__new__(*args, **wargs)
#      protoobj.__init__(*args, **wargs)
#      return protoobj

让我们试试这个:

>>> class Point:
>>>     pass
>>> type(Point)
<class 'type'>
>>> type.__call__(int, 2)
2
>>> type.__call__(Point)
<__main__.Point object at 0x0000000003105C18>

它似乎工作!是的!

【讨论】:

    猜你喜欢
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多