一,类和实例

1,类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响;

class Student(object):
    pass

定义类:定义类是通过class关键字,class后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object)

表示该类是从哪个类继承下来的,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。

定义好了Student类,就可以根据Student类创建出Student的实例,创建实例是通过类名+()实现的:

Student
Student
Student
bart = Student()

2,方法就是与实例绑定的函数,和普通函数不同,方法可以直接访问实例的数据;

   方法就是类的功能,也就是定义在类里面的函数,它实现了某个功能

   通过在实例上调用方法,我们就直接操作了对象内部的数据,但无需知道方法内部的实现细节。

   和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同

__init__
name
score
class Student(object):
    def __init__(self, name, score):#构造函数:就是类在实例化的时候做的某些初始化操作


          = name
self.score = score
def __del__(self):#析构函数:析构函数就是这个实例在销毁的时候做的一些操作。
       self.cur.close()
       self.coon.close()

注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。

有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去:

bart = Student('Bart Simpson', 59)
self
import pymysql
class OpMySql1:  #经典类
   pass

class OpMySql(object):#新式类
   def __init__(self,host,user,password,db,port=3306,charset='utf8'):#构造函数,就是类在实例化的时候做的某些初始化操作
      schema = {
         'user':user,
         'host':host,
         'password':password,
         'db':db,
         'port':port,
         'charset':charset
      }
      try:
         self.coon = pymysql.connect(**schema)
      except Exception as e:
         print('数据库连接异常!%s'%e)
         quit('数据库连接异常!%s'%e)
      else:#没有出异常的情况下,建立游标
         self.cur = self.coon.cursor(cursor=pymysql.cursors.DictCursor)

   def execute(self,sql):#类的方法
      try:
         self.cur.execute(sql)
      except Exception as e:
         print('sql有错误%s'%e)
         return e
      if sql[:6].upper()=='SELECT':
         return self.cur.fetchall()
      else:#其他sql语句的话
         self.coon.commit()
         return 'ok'

   def __del__(self):#析构函数:析构函数就是这个实例在销毁的时候做的一些操作。
      self.cur.close()
      self.coon.close()

res = OpMySql('211.149.218.16','jxz','123456',db='jxz')  #实例化
print(res.execute('select * from stu;'))
print(res.execute('select * from stu;'))
print(res.execute('select * from stu;'))

二,数据封装
把一些功能的实现细节不对外暴露,类中对数据的赋值、内部调用对外部用户是透明的,这使类变成了一个胶囊或容器,里面包含着类的数据和方法。
class Student(object):

    def __init__(self, name, score):
         = name
        self.score = score

    def print_score(self):#类的方法
        print('%s: %s' % (, self.score))
self
self
print(bart.print_score())

这样一来,我们从外部看Student类,就只需要知道,创建实例需要给出namescore,而如何打印,都是在Student类的内部定义的,这些数据和逻辑被“封装”起来了,调用很容易,但却不用知道内部实现的细节。

封装的另一个好处是可以给Student类增加新的方法,比如get_grade

class Student(object):
    ...

    def get_grade(self):
        if self.score >= 90:
            return 'A'
        elif self.score >= 60:
            return 'B'
        else:
            return 'C'

由于Python是动态语言,根据类创建的实例可以任意绑定属性。

给实例绑定属性的方法是通过实例变量,或者通过self变量:

class Student(object):
    def __init__(self, name):
         = name#实例变量,必须实例化之后才能用,成员变量
s = Student('Bob') s.score = 90
Student
Student
class Student(object):
    name = 'Student'#类变量
当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到
__
__
class Student(object):

    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_score(self):
        print('%s: %s' % (self.__name, self.__score))
实例变量.__name
实例变量.__score
bart = Student('Bart Simpson', 59)
print(bart.__name)
输出结果:
AttributeError: 'Student' object has no attribute '__name'
五,继承和多态(python 不支持多态)
继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写
当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Super class)
class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):#对于Dog来说,Animal就是它的父类,对于Animal来说,Dog就是它的子类
 
   pass
class Cat(Animal): 
   pass
继承有最大的好处是子类获得了父类的全部功能。由于Animial实现了run()方法,因此,Dog和Cat作为它的子类,什么事也没干,就自动拥有了run()方法

Animial
run()
Dog
Cat
run()
dog = Dog()
dog.run()

cat = Cat()
cat.run()
Animal is running...
Animal is running...
class Animal(object):#父类
    def run(self):
        print('Animal is running...')

class Dog(Animal):#子类也可以将父类不适合的方法覆盖重写
    def run(self):
        print('Dog is running...')#修改

class Cat(Animal):
    def run(self):
        print('Cat is running...')
六,使用@property(属性方法)
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改:
s = Student()
s.score = 9999
set_score()
get_score()
set_score()
class Student(object):

    def get_score(self):
         return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
@property
@property
@property
@property
@score.setter
s = Student()
s.score = 60
print(s.score) #输出结果:60
s.score = 9999
print(s.score)  #输出结果:ValueError: score must between 0 ~ 100!

注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。

还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:

class Student(object):

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth
birth
age
age
birth

小结

@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。

七,静态方法和类方法

@staticmethod #静态方法
def other():
   print('我是other')
@classmethod#类方法,也不需要实例化,直接就能用。它静态方法高级一点
#它可以使用类变量和类方法。
def class_fun(cls):
   print(cls.xiaohei)
   cls.class_fun2()
@classmethod
def class_fun2(cls):
   print('我是类方法2')
静态方法
   不需要实例化就能直接用的,其实和类没有什么关系,就是一个普通的函数
   写在了类里面而已,也用不了self的那些东西,也调用不类里面的其他函数。