Python OOP - 属性对象是否在对象中?

时间:2015-10-11 15:13:46

标签: python class oop variables

在课堂和OOP方面,我有一些问题。

# Lets say we have this variable.
my_integer = 15

现在,如果我做对了,当发生赋值时,Python会创建一个int类的对象,其值为15,然后由定义为 my_integer 的name-tag引用。

# Now we "change" it.
my_integer = 50

现在应该创建一个值为50的新int对象,但是引用标记会切换到新创建的对象,从而使一个没有标记的对象留下来进行垃圾处理。

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()对象中创建一个整数对象吗?

当对象中有多个对象时,它是不是很复杂?

我对前两点的理解是否正确?

1 个答案:

答案 0 :(得分: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>

似乎工作!是的!