如何给实例添加 方法?

class A(){
}
class B extend A{
    function test(){
        
    }
}

假如目前已经有一个 A类的实例 , 如何让这个 实例 也能够使用 test 方法呢?
不能修改 A 类

php 和 python 分别怎么做? 如果可以的话

之前写php时候, 用其他的包, 会遇到调用结果返回的已经是实例对象了, 但是期望增加一些自己的方法, 但是原始包又没有给 注入依赖 的入口

ps: 把A的实例, 转换为B的实例

//我要的就是这样的 magic 函数
a = new A();
function magic(A &a){
    //%^&*$%^#$%^
}
//使得 
get_class(magic(a)) == B   //<===> true

想知道有没有语法层面就能解决这个问题的

阅读 5.1k
3 个回答

Python里可以实现动态的绑定实例方法,举例如下:

class A:
    pass

class B(A):
    def test(self):
        print "B's test method"

a = A()

现在给a绑定一个test方法,注意的是不能绑定到B的test,你不能A.test = B.test

def test(self):
    print 'outside test method'

A.test = test
a.test()

给已有的类或实例增加方法,对于动态语言很容易。例如对js:

function A(){
    this.name = 'a'
}

var a = new A

给a添加一个test方法

a.test = function(){
    console.log(this.name, 'test')
}

或者在原型上添加:

A.prototype.test = function(){
    console.log(this.name, 'test')
}

调用a.test(),都会输出: "a test"

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题