python简说(二十五)面向对象

面向对象编程:

一个种类、一个模型
实例、实例化、对象
实例、对象:
根据模型制作出来的东西。
实例化:
就是做东西的这个过程。
    class My:
    my=My()
私有
方法
类里面的函数
属性
类里面的变量
构造函数
类在实例化的时候会自动执行的一个函数
class MyDb:
def __init__(self,host,user,password,db,port=3306,charset='utf8'):#构造函数,
print('连接数据库')
self.conn = pymysql.connect(host=host,user=user,password=password,
db=db,port=port,charset=charset)
self.cur = self.conn.cursor()

def execute_one(self,sql):
print('返回单条数据')
self.cur.execute(sql)
res = self.cur.fetchone()
return res
my=MyDb('127.0.0.3','jxz',123456,'jxz') #实例化
        析构函数
实例在销毁的时候自动执行的函数
def __del__(self):

self
代表的本类对象。
       一个变量前面加了self之后,在整个类中的其他函数都可以用了
类变量:
就在直接在类下面定义的变量,没有加self的,每个实例都可以用
class Car:
wheel = 4 #类变量
def __init__(self,color,p):
self.color = color #实例变量
self.p = p
        类方法:
1、不需要实例化就可以调用
2、它可以使用类变量
3、调用其他的类方法。
4、它不可以使用实例方法、实例变量
如果类里面的这个方法,它并没有使用到其他的实例变量、或者其他实例方法,那么就给他定义成类方法
    class Car:
      @classmethod
      def check_wheel(cls):
         print(cls.wheel)
    Car.check_wheel()
静态方法:
1、不需要实例化就可以调用的
2、它就是一个定义在类里面的普通函数,不能使用实例变量、实例方法、不能使用类变量、类方法。
    @staticmethod
    def help():
      print('uuu')
属性方法:
看起来像变量的一个方法。
  class My
    @property
    def name(self):
      return 'a'
my=My()
  my.name

实例变量:
self.xxx = xxx
加了self的变量才是实例变量,必须得实例化之后才可以使用

实例方法:
需要传self的方法,都是实例方法,必须得实例化之后才可以使用
实例方法里面可以随便通过self来调用实例方法,类方法,静态方法,类变量。
私有:
变量、函数,前面加两个下划线就代表是一个私有的,只能在类里面用。
        def test(self):
          self.__password = 123456
        继承:
class Lm:
money = 1000000
house = 5
def driver(self):
print('会开车')

class Mcb(Lm):
def about_me(self):
print('我有 %s 钱 ,%s 房子'%(self.money,self.house))
self.driver()
super:
在父类某个方法的基础上再增加新功能:
super().xxx()
super()会自动找到父类

class Car:
def run(self,):
print('running...')
return 'abc'
class NewCar(Car):
def run1(self):
res = super().run()# super()的意思就是找到父类
print('fly...',res)
 
posted @ 2019-01-07 14:12  狐觞  阅读(210)  评论(0编辑  收藏  举报