class A:
def __init__(self, name):
self.name = name
self.S1()
def S1(self):
self.s2 = []
self.s2.append(self.name*2)
A1 = A('python')
A1.s2
在__init_()方法中用实例对方法S1进行初始化, 因此可以直接用实例初始化A的类方法S1下定义的s2变量。结果如下:
['pythonpython']
如果不初始化,
class A:
def __init__(self, name):
self.name = name
def S1(self):
self.s2 = []
self.s2.append(self.name*2)
A1 = A('python')
A1.s2
会报错
AttributeError: 'A' object has no attribute 's2'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-49-2e435ef4fdb8> in <module>
9
10 A1 = A('python')
---> 11 A1.s2
12
13
AttributeError: 'A' object has no attribute 's2'