如果我有类似的东西
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)
650*_*502 23
在Python中,import语句用于模块,而不是类......所以要导入一个类,你需要类似的东西
from mymodule import MyClass
Run Code Online (Sandbox Code Playgroud)
更多的问题是答案是肯定的.在Python中,类只是常规对象,而类方法只是存储在对象属性中的函数.
此外,Python中对象实例的属性是动态的(您可以在运行时添加新的对象属性),这一事实与前一个相结合意味着您可以在运行时向类添加新方法.
class MyClass:
def __init__(self, x):
self.x = x
...
obj = MyClass(42)
def new_method(self):
print "x attribute is", self.x
MyClass.new_method = new_method
obj.new_method()
Run Code Online (Sandbox Code Playgroud)
这怎么办?当你输入
obj.new_method()
Run Code Online (Sandbox Code Playgroud)
Python将执行以下操作:
寻找new_method
对象内部obj
.
没有找到它作为实例属性,它将尝试在类对象(可用obj.__class__
)中查找它将找到该函数的位置.
现在有一些技巧,因为Python会注意到它发现的是一个函数,因此将它"封装"在一个闭包中以创建所谓的"绑定方法".这是必需的,因为当你调用时obj.new_method()
你想要调用MyClass.new_method(obj)
...换句话说,绑定函数obj
来创建绑定方法就是需要添加self
参数.
这个绑定方法是返回的obj.new_method
,然后由于()
该行代码的结束而最终调用它.
如果对类的搜索也没有成功,则父类也都按特定顺序搜索,以查找继承的方法和属性,因此事情稍微复杂一点.