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

标签 python oop delegates delegation

我以前一直以为python后面跟着一个''Class Based Inheritance仅(也许我的知识有限)。但在阅读 JavaScript 后,它显示了 '' Prototype Delegation Based Model ,我意识到即使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'>

我的意思是当前实例是对类型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 的类;它删除名称 A。由于还有另一个对该类的引用(即 b.__class__),因此该类仍然存在,并且所有查找都将照常进行。

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

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

关于python - 基于原型(prototype)委托(delegate)的模型如何在 Python 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672721/

相关文章:

python - 为什么 pip install mysql-connector 失败?

php - PDO 错误 : Call to a member function prepare() on null

python - 如何表达调用派生虚拟的基类方法?

ios - self.tableView.delegate = self swift

ios - 从 Swift iOS 中的模态视图中获取值(value)

Python:urlretrieve PDF 下载

python - 以下Theano方法中参数更新方式是否有错误?

python - Pickle dump 替换当前文件数据

c# - 什么是阅读 ISomething : ISomethingElse 的正确方法

c# - 不能通过委托(delegate)