【问题标题】:How do I print a variable that is within def - python如何打印 def - python 中的变量
【发布时间】:2017-02-17 13:59:08
【问题描述】:
我要打印变量的内容,尽管变量存在于 def 中。这是我的代码的样子:
def count_words():
var_one = "hello world"
print count_words.var_one
以上行不通。我收到以下错误:
AttributeError: 'function' object has no attribute 'hello'
我该如何解决这个问题?
【问题讨论】:
标签:
python
function
variables
count
【解决方案1】:
你需要返回一些东西:
def count_words():
var_one = "hello world"
return var_one
print(count_words())
现在 print 语句正在调用一个函数并打印返回的值。
【解决方案2】:
如果你想打印一个变量的内容,你需要确保变量退出并且你可以访问。根据你的代码,你不能做你想做的事,因为这两个条件都不满足。写入文件的代码和执行后的代码不是同一个概念。写在文件中的代码就像一本食谱,当计算机执行代码时,就像厨师在按照食谱烹饪东西一样。没有厨师做饭,你不能强硬的成分(打印变量)(变量不会在运行环境中退出,只在文件中退出)。如果厨师不允许您将其变硬(您没有打印变量的可访问性),您也不能将其变硬。一个函数就像一个菜谱,它告诉你如何做一些烹饪,但它只保留在文件(文件)中,直到你按照菜谱进行烹饪。然后就可以根据answer打印变量了
【解决方案3】:
尼克的答案可能是你想要的。附带说明一下,您可能希望使用一个类并像这样访问它的属性:
class CountWords():
var_one = "hello world" # this is the attribute
count_words = CountWords() # instantiate the class
print(count_words.var_one) # access the class' attribute