学习Python基础--------6面对对象进阶

上节回顾

 


属性
实例变量(存在每个实例的内存里)
类变量(存在类里,共享使用)
私有属性__var

方法
构造方法 __init__
析构方法 __del__ (实例打开链接临时文件关闭后销毁)
私有方法

对象:实例化一个类之后得到的对象

 


封装
把一些功能的实现细节不对外暴露

续承
继承方式
继承
组合

代码的重用
单级成
多继承
2.7 广度优先新式类,深度优先经典类
3.0 都是广度优先
class Foo(School)

  def __init__(self,name,age,sex,salary,course):
  #新式类
  super(Foo,self).__init__(name,age,sex)
  #经典类
  School.__init__(self,name,age,sex)
  #组合
  self.person = person

    self.salary = salary
    self.course = course
多态
接口重用,一种接口多种实现

 

静态方法

通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法?

普通方法可以实例化调用,并且方法里可以通过self.通用实例变量或类变量,但静态方法是不可以访问实例变量和实例变量,它与类唯一的关联就是需要通过类名来调用这个方法

class Dog(object):
    def __init__(self,name):
        self.name = name

  #方法
    def eat(self,food):
        print('%s is eating %s'%(self.name,food))

d = Dog('cehngronghua')

d.eat('baozi')

#输出cehngronghua is eating baiozi



##############
class Dog(object):
    def __init__(self,name):
        self.name = name

    @staticmethod    #和类什么关系  ,只是相当于函数
    def eat(self,food):
        print('%s is eating %s'%(self.name,food))

d = Dog('cehngronghua')

d.eat(d,'zhiyu')   #独立的函数重新传入值
#输出  cehngronghua is eating zhiyu

类方法

类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量

# Author:Zhiyu Su

class Dog(object):
    name = 1233
    def __init__(self,name):
        self.name = name

    @classmethod
    def eat(self):
        print('%s is eating %s'%(self.name,'dd'))

d = Dog('cehngronghua')

d.eat() 
#输出  1233 is eating dd    直接调用类的变量

 

属性方法

把一个方法变成一个属性  所以调用直接调用不用输入括号

# Author:Zhiyu Su

class Dog(object):

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

    @property   #attribute  属性
    def eat(self):
        print('%s is eating %s'%(self.name,'dd'))

d = Dog('cehngronghua')

# d.eat()#调用时会报错'NoneType' object is not callable

d.eat
#输出cehngronghua is eating dd




属性方法@eat.setter
##################
# Author:Zhiyu Su

class Dog(object):

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


    #方法变成属性
    @property   #attribute  属性
    def eat(self):
        print('%s is eating %s'%(self.name,'dd'))

    #如果要给eat设置属性需要重新设立一个eat
    @eat.setter
    def eat(self, food):
        print('set to food :', food)

d = Dog('cehngronghua')

# d.eat()#调用时会报错'NoneType' object is not callable

d.eat

d.eat = 'baozi'

#  输出 cehngronghua is eating dd    set to food : baozi

##################

#调用 @eat.deleter删除

# Author:Zhiyu Su

class Dog(object):

    def __init__(self,name):
        self.name = name
        self.__food = None



    @property
    def eat(self):
        print('%s is eating %s'%(self.name,self.__food))


    @eat.setter
    def eat(self, food):
        print('set to food :', food)
        self.__food = food

    @eat.deleter
    def eat(self):
        del self.__food
        print('删完了')

d = Dog('cehngronghua')

d.eat#调用 @property  eat

d.eat = 'baozi'  #调用@eat.setter
del d.eat        # 调用 @eat.deleter

属性方法的实例

# Author:Zhiyu Su

class Flight(object):
    def __init__(self,name):
        self.flight_name = name


    def checking_status(self):
        print('cheking flight %s tatus' % self.flight_name)
        return 1

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0:
            print('filight got cancelend...')
        elif status == 1:
            print('flighrt is arried...')
        elif status == 2:
            print('filght has de partured already...')
        else:
            print('cannot confirm the flight staus....,please check later')
    @flight_status.setter
    def flight_status(self,status):
        print('Flight %s has changed status to %s'%(self.flight_name,status))

f = Flight('CA980')
f.flight_status
#对用户端口
f.flight_status = 2
f.flight_status
View Code

 

类的特殊成员方法

1.__doc__ 表示类的描述信息

# Author:Zhiyu Su

class Dog(object):
    '''这个对象是狗'''

    def __init__(self,name):
        self.name = name
        self.__food = None

    @property
    def eat(self):
        print('%s is eating %s'%(self.name,self.__food))



d = Dog('cehngronghua')

print(Dog.__doc__)
#输出 打印类的描述性信息‘这个对象是狗’
View Code

2.__module__和__class__

__module__ 表示当前操作的对象在哪个模块

__class__  表示当前操作的对象的类是什么

 3.__init__ 构造方法,通过类创建对象时,自动触发执行

4.__del__构造方法,当对象在内存中被释放时,自动触发执行,注意(如果不写也会执行,类的身就存在__del__方法,重写会覆盖父类方法)

5.__call__对象后面加括号,触发执行注。注意:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

6.__dict__查看类或对象中的所用成员

__dict__

7.__str__如果一个类中定义了__str__方法,那么在打印对象时,默认输出该方法的返回值

# Author:Zhiyu Su

class Dog(object):
    '''这个对象是狗'''

    def __init__(self,name):
        self.name = name
        self.__food = None

    def __str__(self):
        return '<obj:%s>'%self.name

d = Dog('alex')
print(d)
#输出<obj:alex>
View Code

8.__getitem__,__setitem__,__delitem__

用于索引操作,如字典。以上分别表示获取,设置,删除数据

# Author:Zhiyu Su
class Foo(object):
    def __init__(self):
        self.data = {}

    def __getitem__(self, key):
        print('__getitem__',key)
        return self.data.get(key)
    def __setitem__(self, key, value):
        print('__setitem__',key,value)
        self.data[key]= value
    def __delitem__(self, key):
        print('__delitem__',key)


obj = Foo()
obj['name']='alex'

# print(obj.data)
# print(obj['name'])
#打印__setitem__ name alex ,{'name': 'alex'},__getitem__ name,alex

del obj['nam']
#打印 __delitem__ nam  删除取决于__delitem__的功能
View Code

9.__new__,__metaclass__(有点不懂)

# Author:Zhiyu Su

class MyType(object):
    def __init__(self,what,bases = None,dict = None):
        print('__MyType init__')
        super(MyType,self).__init__(what,bases,dict)

    def __call__(self, *args, **kwargs):
        print('MyType __call___')
        obj = self.__new__(self,*args,**kwargs)  #调用了Foo里new
        self.__init__(obj,*args,**kwargs)     #调用  Foo里的init



class Foo(object):
    __metaclass__ = MyType

    def __init__(self,name):
        self.name = name
        print('Foo __init__')

    def __new__(cls, *args, **kwargs):
        print('Foo __new__')
        return object.__new__(cls)  #继承父类的__new__方法

obj = Foo('alex')
#Foo __new__  先于__init__
#Foo __init__
#通过new实例化的  然后调用init
#new是用来创建实例的   相对自己写的类来进行定义
View Code

 

反射

通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法

  hasattr (obj,name_str),判断一个对象是否有对应的name_str字符串方法

  getattr   (obj,name_str)    ,根据字符串取获取obj对象里的对象方法和内存地址

  setattr   (obj,'y','z')            x.y ='v'

  delattr    (obj,'y','z')      删除指定的值

# Author:Zhiyu Su
def bulk(self):
    print('%s is yelling'%self.name)
class Dog(object):

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

    def eat(self,ftp):
        print('%s is eating  %s'%(self.name,ftp))


d = Dog('NiuHanYang')
choice = input('>>>>:').strip()

if hasattr(d,choice):   #判断d里是否有chioce
    delattr(d,choice)

    # attr = getattr(d,choice)
    # print(attr)
    # fun('chengrong')
    # setattr(d,choice,'rong')
else:
    # setattr(d,choice,bulk)
    # d.talk(d)
    setattr(d,choice,22)
    print(getattr(d,choice))

print(d.name)
View Code

 

异常处理

# Author:Zhiyu Su
names = ['alex','jack']
data = {}

try:
    names[3]
    # data['name']
# except Exception as e:    #包含所有错误,不建议使用
#     print('出错了',e)



except (KeyError,IndexError) as a:
    print('没有这个',a)


# except IndexError as e:
#     print('列表操作错误',e)

finally:
    print('出错不出错都执行')
View Code

自定义异常

# Author:Zhiyu Su

class ALexException(Exception):
    def __init__(self,msg):
        self.message = msg
    def __str__(self):     #类打印返回格式
        return self.message

try:
    raise ALexException('我的异常')
except ALexException as e:
    print(e)

 

posted @ 2017-09-21 23:02  那是谁的领地  阅读(174)  评论(0)    收藏  举报