Skip to main content
 首页 » 编程设计

python之基于原型(prototype)委托(delegate)的模型如何在 Python 中工作

2024年10月24日8开发

我以前以为python后面跟着一个'' Class Based Inheritance只有(也许我的知识有限)。但是在阅读了显示 '' Prototype Delegation Based Model 的 JavaScript 之后, 我意识到即使是 python 也显示了基于原型(prototype)实现的一些特性

class A(object): 
 
  def __init__(self, a): 
    self.a = a 
 
  def square(self): 
    return self.a * self.a 
 
a = A(10) 
print(a.a) #10 
 
A.b = 20 # a new Property of the class 
print(a.b) # 20 - available via "delegation" for the "a" instance 

同样,就像在基于原型(prototype)的模型中一样,可以在运行时更改对象的原型(prototype)。

class B(object): 
  """ Empty class B""" 
  pass 
 
b = B() # an instance of the class B 
b.__class__ = A # changing class (prototype) dynamically 
print (b.__dict__) # {} 
b.a = 20 # create a new property 
 
print(b.square()) # 400 - method of the class A is available 

即使我删除了对类 A 的显式引用

del A # deleting the explicit reference on classes 
# print(A) --> error 

A类的方法对对象b仍然可用

print(b.square()) # 400 

还有当我写 b.__class__ = A

print(b.__class__) #<class '__main__.A'> 

我的意思是当前实例是对 type A 的引用,对吗? 因为当我打印

print(A.__class__) # <type 'type'> 

意思是A是对类型type的引用。

因为 python 中的一切都是一个对象,而且我从来没有明确地创建过 A 的任何对象。此委托(delegate)模型是否隐式创建了 A 的对象?如果不是,那么这个模型是如何工作的?对象 b 是否保持对 A 或 A 的对象的隐式引用,以防它按上述要求创建对象?

请您参考如下方法:

Since everything in python is an object and i've never created any Object of A explicitly. Does This delegation model creates the Object Of A Implicitly ?

没有。

If not then how does this model work ?

每个对象都知道它的类别(您可以更改)。属性查找是动态发生的:每次你尝试访问一个属性(包括像 .square() 这样的方法)时,Python 首先查看实例是否具有属性本身,然后查看任何 __class__ 实例在那一刻拥有,并在那里寻找。

Does the object b maintain the implicit reference to A or object of A in case it creates an Object as asked above ?

当您执行 b.__class__ = A 时,您明确地为 b 提供了对 A 的引用。请注意,del A 不会删除名为 A 的类;它删除了 name A。由于存在对该类的另一个引用(即 b.__class__),该类仍然存在并且所有查找将照常进行。

它在 Python 中的基本工作方式是每个对象都有一个父类(super class)列表,每次您尝试访问对象的属性时都会按顺序检查这些父类(super class)。您可以更改该列表(通过分配给 __class__,甚至通过更改其类或父类(super class)的 __bases__ 属性)。

我不太确定您认为这与原型(prototype)继承有什么关系。原型(prototype)继承的主要内容是类和实例之间没有区别;您可以直接从任何其他实例创建一个“实例”。这实际上不是 Python 的工作方式,因为类及其实例具有不同的行为,并且您不能像从类创建实例那样直接“克隆”实例。