简体   繁体   English

从 python 中的 function 外部重新分配 function 变量

[英]Reassign function variable from outside the function in python

I'm new to coding.我是编码新手。 I'm trying to access a function variable from outside the function.我正在尝试从 function 外部访问 function 变量。

def calculate_age():
    age =10

my_age=calculate_age ()
my_age.calculate_age.age=20

Error错误

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    my_age.calculate_age.age=20
AttributeError: 'NoneType' object has no attribute 'calculate_age'

I am writing an answer as I can't comment yet.我正在写一个答案,因为我还不能发表评论。 Functions should have a "return" statement, which passes on the output of the function.函数应该有一个“return”语句,它传递 function 的 output。 In your case you'd need to have it like this:在您的情况下,您需要这样:

def calculate_age():
    age =10  # ideally have a calculation here
    return age

Have a look on this page for how functions work.查看此页面以了解函数的工作原理。

You can't access that variable outside of that function.您无法在 function 之外访问该变量。 Look at this:看这个:

def calculate_age():
    age = 10  # this variable is local to the function. you can't access it anywhere else.
    return age


my_age = calculate_age()  # set a variable outside the function.
print(my_age)
# prints 10

my_age = 20 # change the variable
print(my_age)
# prints 20

This is called "scope" and you can read about it here .这称为“范围”,您可以在此处阅读

Like other users already mentioned, you can't do that using a function.像已经提到的其他用户一样,您不能使用 function 来做到这一点。 However you can get this behavior using an object or in python called a class.但是,您可以使用 object 或在称为 class 的 python 中获得此行为。 extra info here额外信息在这里

As an example, you could create a class Person.例如,您可以创建一个 class 人员。

class Person():
    age = 10
    height = 1.5
    lan = "Eng"

paul = Person()

Now you can use the instance of Person called "paul" to do.现在你可以使用名为“paul”的Person实例来做。

paul.age #returns 10
paul.age = 20
paul.age #returns 20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM