直接上代码:
class Person(object):
name = 'python'
age = 18
def __init__(self):
self.sex = 'boy'
self.like = 'papapa'
@staticmethod
def stat_func():
print 'this is stat_func'
@classmethod
def class_func(cls):
print 'class_func'
person = Person()
print 'Person.__dict__: ', Person.__dict__
print 'person.__dict__: ', person.__dict__
运行结果:
Person.__dict__: {'__module__': '__main__', 'name': 'python', '__init__': <function __init__ at 0x000000000385B518>, 'class_func': <classmethod object at 0x0000000003847F78>, '__dict__': <attribute '__dict__' of 'Person' objects>, 'age': 18, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'stat_func': <staticmethod object at 0x00000000037CFAF8>}
person.__dict__: {'like': 'papapa', 'sex': 'boy'}
由此可见, 类的普通方法、类方法、静态方法、全局变量以及一些内置的属性都是放在类对象__dict__里
而实例对象中存储了一些self.xxx的一些东西
在类的继承中,子类有自己的__dict__, 父类也有自己的__dict__,子类的全局变量和方法放在子类的dict中,父类的放在父类dict中。
class Person(object):
name = 'python'
age = 18
def __init__(self):
self.sex = 'boy'
self.like = 'papapa'
@staticmethod
def stat_func():
print 'this is stat_func'
@classmethod
def class_func(cls):
print 'class_func'
class Hero(Person):
name = 'super man'
age = 1000
def __init__(self):
super(Hero, self).__init__()
self.is_good = 'yes'
self.power = 'fly'
person = Person()
print 'Person.__dict__: ', Person.__dict__
print 'person.__dict__: ', person.__dict__
hero = Hero()
print 'Hero.__dict__: ', Hero.__dict__
print 'hero.__dict__: ', hero.__dict__
运行结果:
Person.__dict__: {'__module__': '__main__', 'name': 'python', '__init__': <function __init__ at 0x000000000374B518>, 'class_func': <classmethod object at 0x0000000003750048>, '__dict__': <attribute '__dict__' of 'Person' objects>, 'age': 18, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'stat_func': <staticmethod object at 0x0000000003737FD8>}
person.__dict__: {'like': 'papapa', 'sex': 'boy'}
Hero.__dict__: {'age': 1000, '__doc__': None, '__module__': '__main__', '__init__': <function __init__ at 0x000000000374B668>, 'name': 'super man'}
hero.__dict__: {'is_good': 'yes', 'like': 'papapa', 'power': 'fly', 'sex': 'boy'}
从运行结果可以看出,类对象的__dict__虽然没有继承父类的,但是实例对象继承了父类的实例属性