我这样做:
def set_property(property,value):
def get_property(property):
Run Code Online (Sandbox Code Playgroud)
要么
object.property = value
value = object.property
Run Code Online (Sandbox Code Playgroud)
我是Python的新手,所以我还在探索语法,我想对此做一些建议.
我有一个非常基本的问题.
假设我调用一个函数,例如,
def foo():
x = 'hello world'
Run Code Online (Sandbox Code Playgroud)
如何让函数以这样的方式返回x,我可以将它用作另一个函数的输入或者在程序体内使用变量?
当我使用return并在另一个函数中调用该变量时,我得到一个NameError.
do_something.n每次调用函数时,函数属性都会递增.
让我感到困扰的是我在函数do_something.n=0 之外声明了属性.
我回答了使用queue.PriorityQueue的问题,不关心使用"函数属性"进行比较以提供与PriorityQueue一起使用的独特计数器 - MartijnPieters有一个更好的解决方案)
MCVE:
def do_something():
do_something.n += 1
return do_something.n
# need to declare do_something.n before usign it, else
# AttributeError: 'function' object has no attribute 'n'
# on first call of do_something() occures
do_something.n = 0
for _ in range(10):
print(do_something()) # prints 1 to 10
Run Code Online (Sandbox Code Playgroud)
还有什么其他方法来定义函数"内部"的属性,以便在AttributeError: 'function' object has no attribute 'n'忘记它时避免使用它?
从评论中编辑了很多其他方式:
我有一个返回字典的函数.
我希望能够在代码中多次访问和使用该字典,而无需每次都调用生成该字典的函数.换句话说,调用函数一次,但使用它返回多次的字典.
所以这样,字典只构造一次(并且可能存储在某个地方?),但在脚本中多次调用和使用.
def function_to_produce_dict():
dict = {}
# something
# something that builds the dictionary
return dict
create_dict = function_to_product_dict()
# other code that will need to work with the create_dict dictionary.
# without the need to keep constructing it any time that we need it.
Run Code Online (Sandbox Code Playgroud)
我已阅读其他帖子,例如: 在不使用`global`的情况下访问函数外部的函数变量
但我不确定通过将函数声明为全局而使用function_to_produce_dict()将使字典无需每次构建都可以访问,通过一次又一次地调用该函数.
这可能吗?