[英]How to reference definition variables nested in a class from main
I would like to know how (in Python) to reference a variable that is inside a def, inside a class.我想知道如何(在 Python 中)引用 def 内、类内的变量。 For example:例如:
class class_name():
.
. # Some more definitions in here
.
def definition_name():
variable_of_interest = 10 # 10 chosen arbitrarily
.
. # Some more definitions in here
.
if __name__ == '__main__':
# Here I want to reference variable_of_interest. Example:
if variable_of_interest = 10
do stuff
Even better, how can I reference the variable in main if the example looks like:更好的是,如果示例如下所示,我如何在 main 中引用变量:
class class_name():
def __init__(self):
# Some code
def _another_definition():
variable_of_interest = 10
if __name__ == '__main__':
#same as before
So basically how do I reference a variable that is placed like Class()>Def()>Def()>Variable in main?那么基本上我如何引用像 Class()>Def()>Def()>Variable 在 main 中放置的变量?
What you're calling a def
is actually either a function or in this case a method in a class.你所称的def
实际上是一个函数,或者在这种情况下是一个类中的方法。
Variables defined in a method are normally not available.方法中定义的变量通常不可用。 That's the whole idea of encapsulation .这就是封装的全部思想。
If you want to access variables in a class they should either class or instance variables.如果要访问类中的变量,则它们应该是类变量或实例变量。
A variable defined in an instance, a member , would need to be accessed as part of an instance of the class.在实例中定义的变量,即成员,需要作为类实例的一部分进行访问。 It's defined in __init__()
.它在__init__()
定义。
For example:例如:
class MyClass:
def __init__(self):
self.data = []
Accessed as:访问方式:
x = MyClass() # instantiate an object of this class
x.data # access instance member
A class variable can be defined at the top of the class definition:可以在类定义的顶部定义类变量:
class MyClass:
"""A simple example class"""
i = 12345
Then it would be accessed with MyClass.i
.然后它会被访问MyClass.i
。
Look at this Python tutorial on classes to understand this better.看看这个关于类的 Python 教程以更好地理解这一点。
If you really want to have a variable in a class method also be accessible directly in the main context then you can make it a global variable by preceding it with global
.如果你真的想让一个类方法中的变量也可以在主上下文中直接访问,那么你可以通过在它前面加上global
来使它成为一个全局变量。 Otherwise variables are by default local and only accessible in the same scope.否则变量默认是本地的,只能在同一范围内访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.