class A():
"""
Class A.
"""
a = 0 #类变量,可直接用类名调用或用实例对象调用
b = 1
def __init__(self): #定义类的初始化方法,作用相当于java里的构造函数
self.b = 2 #实例变量(成员变量),以self.开头来定义
self.c = 3
def test(self): #定义类的普通方法
self.d=4 #定义在普通方法里的成员变量,只有在test()被调用后才初始化
e=5 #局部变量
@staticmethod
def static_test(): #定义静态方法,注意不需要self参数
print('static func')
@classmethod
def class_test(self): #定义类方法,注意需要self参数
print('class func')
obj = A()
print(A.__dict__)
print(obj.__dict__)
输出:
{
'__module__': '__main__',
'__doc__': '\n Class A.\n ',
'a': 0, 'b': 1,
'__init__': <function A.__init__ at 0x0000020A43138948>,
'test': <function A.test at 0x0000020A43140CA8>,
'static_test': <staticmethod object at 0x0000020A43147688>,
'class_test': <classmethod object at 0x0000020A4312AF08>,
'__dict__': <attribute '__dict__' of 'A' objects>,
'__weakref__': <attribute '__weakref__' of 'A' objects>
}
{'b': 2, 'c': 3}
调用test()方法,然后对比一下类的__dict__属性和类对象的__dict__的变化:
class A():
"""
Class A.
"""
a = 0
b = 1
def __init__(self):
self.b = 2
self.c = 3
def test(self):
self.d=4
e=5
@staticmethod
def static_test():
print('static func')
@classmethod
def class_test(self):
print('class func')
obj = A()
obj.test()
print(A.__dict__)
print(obj.__dict__)
输出:
{
'__module__': '__main__',
'__doc__': '\n Class A.\n ',
'a': 0, 'b': 1,
'__init__': <function A.__init__ at 0x000001D1632B8948>,
'test': <function A.test at 0x000001D1632C0CA8>,
'static_test': <staticmethod object at 0x000001D1632AA9C8>,
'class_test': <classmethod object at 0x000001D1632AE408>,
'__dict__': <attribute '__dict__' of 'A' objects>,
'__weakref__': <attribute '__weakref__' of 'A' objects>
}
{'b': 2, 'c': 3, 'd': 4}
9073

被折叠的 条评论
为什么被折叠?



