在我的情况下,我想保存和恢复文件中的一些“普通”变量(即整数,字符串),这最终将作为类属性。这个例子是我最近的地方,通过使用import
:纯文本,Python的语法文件来保存和恢复一些类变量?
a.py
b = 134
a = "hello"
mytest.py
import inspect
class Teost:
from a import *
def __init__(self):
self.c = 12
print(inspect.getmembers(self)) # has a and b
print(self.__dict__) # no a and b
print(self.a) # prints "hello"
xx = Teost()
所以,在这里a.py
作为文件存储变量值(a
和b
)和from a import *
里面该类将它们作为类属性(self.a
和self.b
),这几乎是我想要的。
不幸的是,原来使用出演import
语法类是不可取的:
$ python mytest.py
mytest.py:3: SyntaxWarning: import * only allowed at module level
class Teost:
[('__doc__', None), ('__init__', <bound method Teost.__init__ of <__main__.Teost instance at 0x7fdca368ab90>>), ('__module__', '__main__'), ('a', 'hello'), ('b', 134), ('c', 12)]
{'c': 12}
hello
...所以我得到一个丑陋的“SyntaxWarning:进口*只允许在模块级”,这是我不能让摆脱(除非我禁用警告,我不想这样做)
所以,我有其他选择,使用a.py
(即纯文本,Python语法)编写的文件,并有在它的变量最终作为一些类属性?
(我见过How do I save and restore multiple variables in python?,但我不感兴趣pickle
或shelve
,因为他们都没有在Python语法写,纯文本文件)
谢谢@StephenRauch - 我觉得我最喜欢这种方法,欢呼! – sdaau
等待,但是'setattr(self,name,....)'会将'name'设置为*实例*属性,而不是类属性......尽管如此,您仍然可以在元类中执行此操作。或者使用'setattr(Teost,name,...)'设置一个类属性。 –