我希望能够将属性http://docs.python.org/library/functions.html#property添加到对象(类的特定实例).这可能吗?
关于python中鸭子打孔/猴子修补的其他一些问题:
更新:由delnan在评论中回答
我需要在swig模板类中添加一个新方法,例如:
我在myswig.i中声明了一个模板类,如下所示:
%template(DoubleVector) vector<double>;
Run Code Online (Sandbox Code Playgroud)
这将在生成的.py文件中生成一个名为"DoubleVector"的类,其中包含一些生成的方法.假设它们是func1(),func2()和func3().这些是生成的函数,我无法控制它们.现在,如果我想向这个类(DoubleVector)添加一个名为"func4()"的新方法,我该怎么办呢?可能吗?
我知道一个名为%pythoncode的标识符,但我不能用它来定义这个模板类中的新函数.
我正在尝试编写一个可以轻松扩展的模拟类。为此,我想使用类似于属性的东西,但这也提供了update一种可以针对不同用例以不同方式实现的方法:
class Quantity(object):
def __init__(self, initval=None):
self.value = initval
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = value
def update(self, parent):
"""here the quantity should be updated using also values from
MySimulation, e.g. adding `MySimulation.increment`, but I don't
know how to link to the parent simulation."""
class MySimulation(object):
"this default simulation has only density"
density = Quantity()
increment = 1
def __init__(self, value):
self.density = value
def update(self):
"""this one does not work because …Run Code Online (Sandbox Code Playgroud) 我想知道如何将由某个函数返回的父对象转换为子类.
class A(object):
def __init__():
pass
class B(A):
def functionIneed():
pass
i = module.getObject()# i will get object that is class A
j = B(i)# this will return exception
j.functionIneed()
Run Code Online (Sandbox Code Playgroud)
我无法改变A类.如果可以的话,我会将classIneed实现到A类,但由于代码结构不可能.谢谢
考虑以下代码:
import functools
import inspect
class Foo:
def foo_fn(self, hello, world):
print(hello, world)
class FooWrapper:
def __init__(self, foo_class):
self._foo = foo_class()
for key, value in inspect.getmembers(self._foo):
if inspect.ismethod(value):
bound_fn = functools.partial(self.foo_wrapper_fn, self, value)
setattr(self._foo, key, bound_fn)
def foo_wrapper_fn(self_wrapper, self_foo, bound_method, hello, world):
bound_method(hello, world)
def make_foo(Foo):
wrapper = FooWrapper(Foo)
return wrapper._foo
a = make_foo(Foo)
a.foo_fn("hello", "world")
Run Code Online (Sandbox Code Playgroud)
foo_wrapper_fn()像这样的功能参数如何排序(self_wrapper, self_foo, bound_method, hello, world)?而不是这样:self_wrapper, bound_fn, self_foo, hello, world,由于self_wrapper和bound_fn首先被部分绑定?
对象()调用返回functool.partial (而不是functool.partialmethod)可以 …
这很可能是一个重复的问题,但我不得不问它,因为其他答案对我来说没有帮助,因为我是 pyqt 的新手(几天前从 tkinter 转换而来)。
我想知道是否可以连接到这样的小部件事件:
self.lineEdit = QtGui.QLineEdit(self.frame)
self.lineEdit.keyReleaseEvent(lambda: someFunction(QtCore.Qt.Key_A ))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.horizontalLayout.addWidget(self.lineEdit)
Run Code Online (Sandbox Code Playgroud)
进而...
def someFunction(event):
print(event)
...
Run Code Online (Sandbox Code Playgroud)
我的问题是如何从另一个小部件绑定到特定事件,并将该事件与类似函数的btn.clicked.connect(function_goes_here).
在 tkinter 它是这样的:
self.Entry.bind("<KeyRelease-a>", lambda event: someFunction(event))
Run Code Online (Sandbox Code Playgroud) 我想要一个包装类,其行为与它包装的对象完全相同,只是它添加或覆盖了一些select方法.
我的代码目前看起来像这样:
# Create a wrapper class that equips instances with specified functions
def equipWith(**methods):
class Wrapper(object):
def __init__(self, instance):
object.__setattr__(self, 'instance',instance)
def __setattr__(self, name, value):
object.__setattr__(object.__getattribute__(self,'instance'), name, value)
def __getattribute__(self, name):
instance = object.__getattribute__(self, 'instance')
# If this is a wrapped method, return a bound method
if name in methods: return (lambda *args, **kargs: methods[name](self,*args,**kargs))
# Otherwise, just return attribute of instance
return instance.__getattribute__(name)
return Wrapper
Run Code Online (Sandbox Code Playgroud)
为了测试这个,我写道:
class A(object):
def __init__(self,a):
self.a = a
a = A(10)
W = …Run Code Online (Sandbox Code Playgroud) 我正在使用matplotlib 工具包 ( ) 中模块中的Basemap对象。在的文件(即模块)中,定义了一种在地图上绘制纬度的方法。我的目标是复制该方法以创建一个名为 的新方法,进行一些调整以绘制磁纬度而不是地理纬度。basemapmpl_toolkits.basemap.Basemapbasemap__init__.pympl_toolkits.basemap.__init__drawparallelsdrawmlat
理想情况下,我希望 newdrawmlat等同于原始文件drawparallel(我可以使用 using 调用的 Basemap 实例的绑定方法BasemapInstance.drawmlats()),并且我不想修改原始文件。我将如何做到这一点?
我已经尝试了“配方”的变体MyObj.method = MethodType(new_method, None, MyObj),但是没有在原始源文件中放置任何东西,新方法无法从 Basemap 模块(例如在其 中定义__init__.py)访问全局变量等。
如果我似乎误解了某些东西,我可能有 - 我或多或少是面向对象编程的新手。
由于我通常尝试在matplotlib图中标记我的轴,我发现我经常使用以下内容单独标记x/y/z轴:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
# <plot plot plot>
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
Run Code Online (Sandbox Code Playgroud)
有没有办法将单个轴标签设置减少到一个命令,理想情况是这样的ax.set_labels(['x', 'y', 'z'])?
我有一个代码,我想在类函数中定义一个类函数.这是我想要做的更简单的例子.该计划的目标是打印4.
>>> class bluh:
... def haha(self):
... print 3
... def __init__(self):
... def haha(self):
... print 4
...
>>> x = bluh()
>>> x.haha()
3
Run Code Online (Sandbox Code Playgroud)
我该怎么写这个程序来做我想要的呢?
我有以下代码,这是一个命令行测试
from cmd2 import Cmd
class App(Cmd, object):
def __init__(self, *args, **kwargs):
pass
def do_test(self, line):
'test'
print "parent test"
class App2():
def __init__(self, *args, **kwargs):
pass
def do_test2(self, line):
print "Test2"
app = App()
app.cmdloop()
Run Code Online (Sandbox Code Playgroud)
是否有可能使用额外的功能扩展App类?我知道有以下解决方案
class App2(App):
....
app = App2()
app.cmdloop()
Run Code Online (Sandbox Code Playgroud)
但在我的情况下,我想只运行App并扩展它,如果可能的话.
python ×12
class ×4
methods ×2
python-3.x ×2
axes ×1
events ×1
inheritance ×1
matplotlib ×1
nested ×1
oop ×1
partial ×1
properties ×1
pyqt ×1
swig ×1
templates ×1
wrapper ×1