相关疑难解决方法(0)

将方法添加到现有对象实例

我已经读过可以在Python中向现有对象(即,不在类定义中)添加方法.

我知道这样做并不总是好事.但是人们怎么可能这样做呢?

python oop methods monkeypatching

596
推荐指数
13
解决办法
22万
查看次数

在python中将方法添加到已加载的类/模块中

如果我有类似的东西

import mynewclass
Run Code Online (Sandbox Code Playgroud)

我可以为mynewclass添加一些方法吗?像概念中的以下内容:

def newmethod(self,x):
    return x + self.y

mynewclass.newmethod = newmethod
Run Code Online (Sandbox Code Playgroud)

(我使用的是CPython 2.6)

python

15
推荐指数
2
解决办法
6346
查看次数

运行时更换方法而不更新私有属性

我了解了如何通过浏览这些链接在Python中运行时替换方法.[ Link1,Link2Link3 ].

当我替换A类的"update_private_variable"方法时,它被替换但不更新私有变量.

import types

class A:
    def __init__(self):
        self.__private_variable = None
        self.public_variable = None

    def update_private_variable(self):
        self.__private_variable = "Updated in A"

    def update_public_variable(self):
        self.public_variable = "Updated in A"

    def get_private_variable(self):
        return self.__private_variable

class B:
    def __init__(self):
        self.__private_variable = None
        self.public_variable = None

    def update_private_variable(self):
        self.__private_variable = "Updated in B"

    def update_public_variable(self):
        self.public_variable = "Updated in B"
Run Code Online (Sandbox Code Playgroud)

在没有替换的情况下调用方法:

a_instance  = A()
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints "Updated in A"   
Run Code Online (Sandbox Code Playgroud)

更换后调用方法时:

a_instance  = A()
a_instance.update_private_variable =  types.MethodType(B.update_private_variable, a_instance) …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

6
推荐指数
1
解决办法
90
查看次数

猛击在Python的物产的鸭子

我希望能够将属性http://docs.python.org/library/functions.html#property添加到对象(类的特定实例).这可能吗?

关于python中鸭子打孔/猴子修补的其他一些问题:

将方法添加到现有对象实例

Python:在运行时更改方法和属性

更新:由delnan在评论中回答

在python中动态添加@property

python monkeypatching properties

5
推荐指数
1
解决办法
2780
查看次数

标签 统计

python ×4

monkeypatching ×2

methods ×1

oop ×1

properties ×1

python-3.x ×1