-
类实例化和调用方法
class test(): def __init__(self): pass # 如果不写对象初始化的属性,必须带一个pass,或者直接去掉__init__ def SUM(self, a, b): return a+b def alter_SUM(self, a, b): a, b = b, a return self.SUM(a, b) test1 = test() print(test1.alter_SUM(1,3)) """ 4 """
注意: 类中所有的method都要在入参中添加
self
,并且在method相互引用的时候,需要在method名字前面加上self
下面的写法是不行的,在类里面不能有方法的相互嵌套,否则报错未定义:
class test(): def __init__(self): pass # 如果不写对象初始化的属性,必须带一个pass,或者直接去掉__init__ def SUM(self, a, b): return a+b+add1(a, b) def add_1(a, b): return 1 test1 = test() print(test1.SUM(1,3)) """ NameError: name 'add1' is not defined """
-
方法嵌套
def print_func(): a = 1 print(a) print_func() print(a) """ NameError: name 'a' is not defined """
错误的原因:a属于局部变量,稍微修改一下就可以了:
def print_func(): global a a = 1 print(a) print_func() print(a) """ 1 1 """
嵌套方法的正确操作:
def print_func(): a = 1 def add(): nonlocal a # 不能使用global哦, global是用来在函数或其他局部作用域中使用全局变量, 而nonlocal是为了申明外部嵌套函数内的变量 a+=1 return a return add() print(print_func()) """ 2 """