class a(object): #有的地方在语法构成上需要一行语句(相当于c++里的int i=0),但实际上不需要任何操作,这时候可以使用pass pass >>> a <class '__main__.a'> >>> a.x Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> a.x AttributeError: type object 'a' has no attribute 'x' >>> a.x=1 >>> a.x 1 >>>
class a(object): #这里的init左右各有2个下划线 def __init__(self,m1,m2): self.m1 = m1 self.m2 = m2 print 'constructor: m1 is %s,m2 is %s' %(m1,m2) #这里的self是必需的 def fun(self): print 'test fun()' >>> b = a('1','2') constructor: m1 is 1,m2 is 2 >>> b.m1 '1' >>> b.m2 = '3' >>> b.m2 '3' >>> b.fun() test fun() 要知道一个类有哪些属性 >>> print dir(a) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'fun'] dict返回的是一个字典,它的键(key)是属性名,键值(value)是相应的属性对象的数据值 >>> print a.__dict__ {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'a' objects>, 'fun': <function fun at 0x0000000002ED8048>, '__weakref__': <attribute '__weakref__' of 'a' objects>, '__doc__': None, '__init__': <function __init__ at 0x0000000002ED3F98>}