Python-在类和方法内外使用变量
Python是一种面向对象的编程语言。Python中的几乎所有东西都是具有其属性和方法的对象。类就像对象的构造函数,或者是创建对象的“蓝图”。
只需编写变量名称,任何类或类中的任何方法都可以访问在类外部定义的变量。
示例
# defined outside the class'
# Variable defined outside the class.
outVar = 'outside_class'
print("Outside_class1", outVar)
''' Class one '''
class Ctest:
print("Outside_class2", outVar)
def access_method(self):
print("Outside_class3", outVar)
# Calling method by creating object
uac = Ctest()uac.access_method()
''' Class two '''
class Another_ Ctest_class:
print("Outside_class4", outVar)
def another_access_method(self):
print("Outside_class5", outVar)
# Calling method by creating object
uaac = Another_ Ctest_class()
uaac.another_access_method()
The variables that are defined inside the methods can be accessed within that method only by simply using the variable name.
# defined inside the method'
'''class one'''
class Ctest:
print()
def access_method(self):
# Variable defined inside the method.
inVar = 'inside_method'
print("Inside_method3", inVar)
uac = Ctest()uac.access_method()
'''class two'''
class AnotherCtest:
print()
def access_method(self):
print()uaac = AnotherCtest()uaac.access_method()热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练