如何在python实例方法中创建静态局部变量?
我来自一个C/C++世界,很难用python实现所有OOP类比。我将脚本包装在一个类中,现在在我的如何在python实例方法中创建静态局部变量?,python,oop,Python,Oop,我来自一个C/C++世界,很难用python实现所有OOP类比。我将脚本包装在一个类中,现在在我的log()“private”实例方法中出现此错误: AttributeError:'instancemethod'对象没有属性“计数器” def __log(self, contents): sys.stdout.write(contents)
log()
“private”实例方法中出现此错误:
AttributeError:'instancemethod'对象没有属性“计数器”
def __log(self, contents):
sys.stdout.write(contents)
# Append all writes after the first
if not hasattr(self.__log, "counter"):
self.__log.counter = 1
f = open(self.output_filepath, 'w')
else :
f = open(self.output_filepath, 'a')
f.write(contents)
f.close()
self.\uu log.counter
引用计数器
变量,该变量在\uu log
方法中不存在
如果需要计数器
变量作为对象实例的一部分,请通过self.counter
如果需要类的计数器
是静态的,请在任何方法之外的类定义中定义变量。检查SO问题
如果您确实需要计数器变量作为实例方法的一部分,那么可以通过类名来引用它
python文档是开始学习python中OO概念的好地方。
这意味着您不能向方法添加属性,但可以修改其dict属性:
class Test:
def __log(self, contents):
sys.stdout.write(contents)
# Append all writes after the first
if not "counter" in self.__log.__func__.__dict__:
self.__log.__func__.__dict__["counter"]= 1
f = open(self.output_filepath, 'w')
print 'w'
else :
f = open(self.output_filepath, 'a')
print 'a'
f.write(contents)
f.close()
a = Test()
a._Test__log('') #Prints w
a._Test__log('') #Prints a
b = Test()
b._Test_log('') #Prints a
class WithLog(object):
opened = False
def log(self, contents):
sys.stdout.write(contents)
mode = "a" if self.__class__.opened else "w"
with open(self.output_filepath, mode) as f:
f.write(contents)
self.__class__.opened = True
Python没有静态局部变量。要解决此问题,最好的解决方案是使用class属性:
class Test:
def __log(self, contents):
sys.stdout.write(contents)
# Append all writes after the first
if not "counter" in self.__log.__func__.__dict__:
self.__log.__func__.__dict__["counter"]= 1
f = open(self.output_filepath, 'w')
print 'w'
else :
f = open(self.output_filepath, 'a')
print 'a'
f.write(contents)
f.close()
a = Test()
a._Test__log('') #Prints w
a._Test__log('') #Prints a
b = Test()
b._Test_log('') #Prints a
class WithLog(object):
opened = False
def log(self, contents):
sys.stdout.write(contents)
mode = "a" if self.__class__.opened else "w"
with open(self.output_filepath, mode) as f:
f.write(contents)
self.__class__.opened = True
当然,最好不要经常打开和关闭日志文件……请检查编辑并让我知道这是否是您想要的。有人能用我的答案解释一下问题吗?在函数中添加属性是愚蠢的。Python没有静态的局部变量,您不应该试图强制它们。相反,提出一个Python解决方案来解决这个问题。OP想给函数添加属性,我向他展示了如何做到这一点。他并不是在要求“Pythonic”的解决方案。我认为给他一个糟糕的答案是愚蠢的。如果您正在查看他的Python代码,发现self.\uuuuu log.\uuuu func.\uuuu dict.\uuuu[“counter”]=1
,您不会告诉他更改它吗?我强烈建议您不要使用“private”名称,如“\uuu log”。它们是丑陋的,实际上并不阻止访问。Python与C++有不同的工作。使用它是为了它自己。尽管它们是一个非常强烈的“远离”标志。作为大型Python库的共同开发人员,我可以告诉您,使用下划线向用户发出接口/实现边界的信号是多么重要。双下划线只是说,“我习惯了java或C++,并且希望我的私人关键词回来!”