Skip to content

Instantly share code, notes, and snippets.

@nature-python
Last active August 29, 2015 13:57
Show Gist options
  • Save nature-python/9482293 to your computer and use it in GitHub Desktop.
Save nature-python/9482293 to your computer and use it in GitHub Desktop.
python类的创建继承,classmethod和staticmethod的区别,类变量和实例变量的区别,@Property,新式类(new style class)和经典类( classic class)

#Python类学习

python是面向对象(OOP)的,类是实现面向对象的方式,与其他语言的类略有不同,python的类比较简单。

  • 创建类
class SchoolMember(object):
  def __init__(self,name,age):
    self.name=name
    self.age=age
  def __str__(self):
    return 'name:%s,age:%s'%(self.name,self.age)
  • 继承类
class Teacher(SchoolMember):
  def __init__(self,name,age,salary):
    SchoolMember(self,name,age)
    self.salary=salary
  def __str__(self):
    return SchoolMember.__str__(self)+',salary:%s'%(self.salary)
  • 类变量和实例变量
class Count():
  count=0
  def __init__(self,count):
    self.count=count
    self.__class__.count+=1
>>>ct1=Count(3)
>>>print ct1.count,Count.count
3 1
>>>ct2=Count(-1)
>>>print ct2.count,Count.count
-1 2
  • 装饰符classmethod和staticmethod
class Methods():
  bar=1
  def normal_method(self):
    print 'normal method'
  @classmethod
  def class_method(cls):
    print 'class method,bar is %s'%cls.bar
    cls().normal_method()
  @staticmethod
  def static_method():
    print 'static method,bar is %s'%Methods.bar
>>>Methods.static_method()
static method,bar is 1
>>>Methods.class_method()
class method,bar is 1
normal method
  • 属性@property(getter,setter,deleter)
#方法一
class Pro(object):
  def __init__(self,x):
    self.__x=x
  def getx(self):
    return self.__x
  def setx(self,value):
    self.__x=value
  def delx(self):
    del self.__x
  x=property(getx,setx,delx)
###############################
#方法二
class Pro(object):
  def __init__(self,x):
    self.__x=x
  @property
  def x(self):
    return self.__x
  @x.setter
  def x(self,value):
    self.__x=value
  @x.deleter
  def x(self):
    del self.__x
>>>pro=Pro(3)
>>>print pro.x
3
>>>pro.x=4
>>>print pro.x
4
>>>del pro.x
  • 新式类和经典类
    • 构造方法

      #经典类
      class A:
        pass
      class A():
        pass
      #新式类
      class A(object):
        pass
    • 属性继承顺序

      #经典类:深度优先
      class CA():
        x='a'
      class CB(CA):
        pass
      class CC(CA):
        x='c'
      class CD(CB,CC):
        pass
      #>>>c=CD()
      #>>>print c.x
      #>>>a
      #新式类:广度优先
      class NA():
        x='a'
      class NB(NA):
        pass
      class NC(NA):
        x='c'
      class ND(NB,NC):
        pass
      #>>>n=ND()
      #>>>print n.x
      #>>>c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment