python公共变量
By default all numbers, methods, variables of the class are public in the Python programming language; we can access them outside of the class using the object name.
默认情况下,该类的所有数字,方法和变量在Python编程语言中都是公共的。 我们可以使用对象名称在类外部访问它们。
Consider the given example:
考虑给定的示例:
Here, we have two variables name and age both are initializing with default values ("XYZ" and 0) while declaring the object using __init__ method.
在这里,我们有两个变量name和age都使用默认值( “ XYZ”和0 )初始化,同时使用__init__方法声明对象。
Later, in the program, outside of the class definition – we are assigning some values ("Amit" and 21) to name and age, that is possible only if variables are public.
后来,在程序中,在类定义之外–我们为name和age分配了一些值( “ Amit”和21 ),只有在变量为public的情况下才可能。
Example:
例:
# Python example for public variables
class person:
def __init__(self):
# default values
self.name = "XYZ"
self.age = 0
def printValues(self):
print "Name: ",self.name
print "Age : ",self.age
# Main code
# declare object
p = person()
# print
p.printValues();
# since variables are public by default
# we can access them directly here
p.name = "Amit"
p.age = 21
# print
p.printValues ();
Output
输出量
Name: XYZ
Age : 0
Name: Amit
Age : 21
翻译自: https://www.includehelp.com/python/public-variables.aspx
python公共变量