在__init__和类函数中定义的self变量(成员变量)是一样的,都可以供给所有类函数调用。
类函数中的局部变量,没有加self,不能供其他函数直接使用。
class Member():
num = 0 # 类变量,可以直接用类调用,或用实例对象调用
def __init__(self, x, y):
self.x = x # 实例变量(成员变量),需要它是在类的构造函数内以self.开头来定义的
self.y = y
self.fuc(self.x, self.y)
def add(self):
total = 2 # 局部变量
self.vara = 3 # 虽是以self.给出,但并没有在构造函数中进行初始化
self.varb = 4
fina = (self.x + self.y) * total
return self.vara
def fuc(self, a, b):
self.varc = a # 成员变量,他们在成员函数fuc()中定义,但是在构造函数中调用了fuc()函数
self.vard = b #self 成员变量是可以互用的!!!
self.vara = 5
return self.vara
注意
在写leetcode的时候发现,如果用了类变量,如果是字典的形式,那么会有累积的效应;如果是成员变量则不会出现这个问题。
举例如下:
class Solution(object):
def __init__(self):
self.a = {}
def example(self, b):
self.a[b] = 5
return self.a
class Solution1(object):
a = {}
def example(self, b):
self.a[b] = 5
self.c = 1
return self.a
S = Solution()
h = S.example(8)
print(h) # {8: 5}
S = Solution()
h = S.example(9)
print(h) # {9: 5}
S1 = Solution1()
h = S1.example(8)
print(h) # {8: 5}
S = Solution1()
h = S.example(9)
print(h) # {8: 5, 9: 5}