Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何打印def-python中的变量_Python_Function_Variables_Count - Fatal编程技术网

如何打印def-python中的变量

如何打印def-python中的变量,python,function,variables,count,Python,Function,Variables,Count,我要打印变量的内容,尽管变量存在于def中。这就是我的代码的样子: def count_words(): var_one = "hello world" print count_words.var_one 上述方法不起作用。我得到以下错误: AttributeError: 'function' object has no attribute 'hello' 我该怎么做 您需要返回一些内容: def count_words(): var_one = "hello world"

我要打印变量的内容,尽管变量存在于def中。这就是我的代码的样子:

def count_words():
    var_one = "hello world"

print count_words.var_one
上述方法不起作用。我得到以下错误:

AttributeError: 'function' object has no attribute 'hello'

我该怎么做

您需要返回一些内容:

def count_words():
    var_one = "hello world"
    return var_one

print(count_words())

现在,print语句正在调用函数并打印返回的值。

您需要返回一些内容:

def count_words():
    var_one = "hello world"
    return var_one

print(count_words())

现在print语句正在调用一个函数并打印返回的值。

Nick的答案可能就是您想要的。作为补充说明,您可能希望使用类并访问其属性,如下所示:

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

尼克的答案可能正是你想要的。作为补充说明,您可能希望使用类并访问其属性,如下所示:

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

如果要打印变量的内容,需要确保变量退出并且可以访问。根据你的代码,你不能做你想做的事情,因为这两个条件都不满足。文件中编写的代码和执行后的代码不是相同的概念。写在文件中的代码就像一本烹饪书,当计算机执行代码时,就像厨师根据烹饪书烹饪一样。如果没有cook正在烹调(变量不存在于运行环境中,只存在于文件中),则无法添加配料(打印变量)。如果厨师不允许你硬做,你就不能硬做配料(你没有打印变量的权限)。一个函数就像一个食谱,它告诉你如何烹饪,但它只保留在纸(文件)中,直到你按照食谱烹饪。然后,您可以根据

打印变量如果您想打印变量的内容,您需要确保变量退出并且您可以访问。根据你的代码,你不能做你想做的事情,因为这两个条件都不满足。文件中编写的代码和执行后的代码不是相同的概念。写在文件中的代码就像一本烹饪书,当计算机执行代码时,就像厨师根据烹饪书烹饪一样。如果没有cook正在烹调(变量不存在于运行环境中,只存在于文件中),则无法添加配料(打印变量)。如果厨师不允许你硬做,你就不能硬做配料(你没有打印变量的权限)。一个函数就像一个食谱,它告诉你如何烹饪,但它只保留在纸(文件)中,直到你按照食谱烹饪。然后您可以根据

打印变量您不能在函数中打印变量,因为它需要执行函数…可能的重复您不能在函数中打印变量,因为它需要执行函数…可能的重复