[英]Python OOP - Are attributes objects within objects?
一般而言,关于课程和OOP,我有一些疑问。
# Lets say we have this variable.
my_integer = 15
现在,如果我做对了,当发生赋值时,Python将创建一个int类的对象,其值为15,然后由定义为my_integer的名称标签进行引用 。
# 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()对象内创建一个整数对象吗?
当一个对象中有多个对象时,它会变得有点复杂吗?
我对前两点的理解正确吗?
基本上是。 让我们更仔细地看一下:
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
类的实例创建比上面的样子有些特殊。 每个类实际上都有一个元类 ,它是类的类型。 最终,可能在多层嵌套之后,解析为内置类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>
看来行得通! 是!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.