python类的定义是很方便的
class A(object):
"""docstsadfasdfring for A"""
finger = 10 # class attribute defined here
leg = 2
age = 0
def __init__(self, arg={}):
super(A, self).__init__()
self.arg = arg
self.name = '' # data attribute defined here
self.age = 0 # data attribute和class attribute的区别就是函数的local变量
# 与函数外部变量的区别(把class看成函数)
# special method 特殊方法以__开头和结束
def __setitem__(self, key, item):
self.arg[key] = item
def __getitem__(self, key):
return self.arg[key]
def __repr__(self):
return str(self.name)
# private method 私有方法只以__开头
def __bb(self):
print '__bb'
# public method
def aa(self):
# 类属性应该是和实例无关的,不应该在这里修改,但可以改
self.__class__.finger += 3
# 更不应该这样改类属性,很混乱
# self.finger += 3
# 不应该有类似这样的写法,类属性先定义
self.__class__.name = 'tom'
# 类属性和实例属性同名
self.age += 1
self.__class__.age += 2
# 类方法, 类属性应该在类方法中修改
@classmethod
def heteromorphosis(cls):
cls.leg += 1
# cls.finger == self.__class__.finger
# cls实在类方法中修改类属性,后者是在实例方法中修改类属性,有点不伦不类
cls.finger += 1
a = A()
a.aa()
b = A()
print a.finger, b.finger, A.finger
print A.name, b.name
print a.age, A.age
A.heteromorphosis()
print a.leg, A.finger, a.finger
# encoding: UTF-8
class M(object):
def __init__(self):
# 这些值都存在实例的__dict__里
self.hello = None
self.foo = None
self.ppp = None
m = M()
m.__dict__.update({'hello': 'world', 'foo': 'bar'})
print m.hello
print m.__dict__