class MyClass(object):
def fun(self):
print “I am function”
类的方法中至少有一个参数self
例1:
#!/usr/bin/python
class People(object):
color = 'yellow'
ren = People() //得到的是一个object。<__main__.People object at 0x7f63dc0d6850>
print ren.color //通过对象得到一个属性,叫静态属性
例2:
#!/usr/bin/python
class People(object):
color = 'yellow'
def think(self): // self表示类的本身,表示使用上面的属性
self.color = "black"
print "I am a %s" % self.color
print "I am a thinker"
ren = People() //访问属性和方法,需要先把类实例化。把类赋给一个变量,变量就是一个对象。
print ren.color //通过对象ren访问class里面的方法
ren.think()
类的属性
#!/usr/bin/python
class People(object):
color = 'yellow' //成员对象。类的属性
def think(self):
self.color = "black"
print "I am a %s" % self.color
print "I am a thinker" // 成员函数。类的方法
ren = People() // 这部分把类实例化。产生一个对象,包括三个特性对象句、属性和方法
print ren.color //ren 对象的属性
ren.think() // ren 对象的方法
#!/usr/bin/python
#coding=utf-8
class People(object):
color = 'yellow'
__age = 30
def think(self):
self.color = "black"
print "I am a %s" % self.color
print "I am a thinker"
print self.__age
def __talk(self):
print "i am talking"
def test(self):
print 'test....'
cm = classmethod(test)
#jack = People()
People.cm() //通过classmethod函数处理才能通过类直接调用。动态方法,直接访问类里面某个方法,没有把其它方法和属性加载到内存当中,占用资源很少。
#!/usr/bin/python
#coding=utf-8
class People(object):
color = 'yellow'
__age = 30
def __talk(self):
print "i am talking"
def test(): //因为没有self参数不知道类里面有什么东西,会把所有的方法和属性加载到内存里。静态的速度要比动态快
print 'test....'
print People.__age //没有self,通过类来访问
sm = staticmethod(test)
jack = People()
jack.sm()
People.sm()
用装饰器不需要函数来处理
#!/usr/bin/python
#coding=utf-8
class People(object):
color = 'yellow'
__age = 30
def __talk(self):
print "i am talking"
@classmethod // 装饰器只对下面的函数起作用,表示这个函数是类方法
def test(self):
print 'test....'
@staticmethod
def test1():
print "this is static method"
jack = People()
People.test()