python,即时动态实现一个类
当我重新启动我的电脑时,无法返回向帖子添加评论 - 下面是一个示例,解释保存 class_with_the_methods_used 的含义,
class bank(object):
def __init__(self, bal=0):
self.bal = bal
def deposit(self, amount):
self.bal+=amount
print self.bal
def debit(self, amt):
self.bal-=amt
print self.bal
bank.debit = debit
myacct = bank()
myacct.deposit(1000) # prints 1000
myacct.debit(99) # print 901
dir(myacct) # print [ ....'bal', 'debit', 'deposit']
然后我使用 pickle 并在保存后保存对象 myacct
,重新启动我的 python 并尝试下面的命令,
>>> import pickle
>>> obj = pickle.load(open('bank.pkl'))
>>> dir(obj) # prints [....'bal', 'deposit']
请注意“借方”不在属性之中。所以我的问题是如何使“借记”之类的方法持久存在?
this is related to python, dynamically implement a class onthefly.
when i restarted my pc, couldnt get back to add comments to the post - below is an example to explain what meant by save the class_with_the_methods_used
class bank(object):
def __init__(self, bal=0):
self.bal = bal
def deposit(self, amount):
self.bal+=amount
print self.bal
def debit(self, amt):
self.bal-=amt
print self.bal
bank.debit = debit
myacct = bank()
myacct.deposit(1000) # prints 1000
myacct.debit(99) # print 901
dir(myacct) # print [ ....'bal', 'debit', 'deposit']
then i used pickle and saved the object myacct
after saving, restarted my python and tried the commands below
>>> import pickle
>>> obj = pickle.load(open('bank.pkl'))
>>> dir(obj) # prints [....'bal', 'deposit']
note that 'debit' is not among the attributes . So my problem is how to make methods like 'debit' persistent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看
new
模块 (http://docs.python.org/library/new.html)它有很多用于动态执行操作的工具。您遇到的问题是 debit 不是实例方法,它只是一个普通函数。类中定义的方法与外部定义的函数不同。
Check out the
new
module (http://docs.python.org/library/new.html)It has a lot of tools for doing things dynamically. The problem you are having is debit is not a instance method, it is just a normal function. Methods defined in classes are different than functions defined outside.
这是由于
pickle
转储自定义类的方式造成的。看下面的内容:
您会发现实际上整个实例都没有被腌制;相反,
pickle
只是记录它是Bank
的一个实例,并通过重新实例化Bank
来重新创建它。如果您想正确执行此操作,则必须定义自定义 pickle 协议,这很复杂。This is due to the way
pickle
dumps custom classes.Look at the following:
You'll see that in fact the entire instance isn't pickled; instead,
pickle
simply records that it is an instance ofBank
and recreates it by re-instantiatingBank
. You will have to define a custom pickle protocol if you want to do this properly, which is complicated.