python 学习笔记6

learning python notes 6

Objected Oriented Programming(senior)

1.__slots__

In python, we can dynamically bind method or attribute to an instance. e.g.

class Student(object):
    pass
def setName(self,name):
    self.name=name

# bind attribute to an instance
a=Student()
a.name='chen'
# bind attribute&&method to an instance
Student.age=18

from types import MethodType
Student.setName=MethodType(setName,Student)

Though these methods provide us with convienence, they make the use of class unsafer. Thus, we need some thing to limit the attribute we can add when we create an instance. And that’s it: slots.
When we define a class, we can add an slots attribute to it, which stores the attributes that can be binded to this class. If we bind it to an not stored attribute, explainer will raise an AttributeType error.

2.Using @property

If we pay attention to packaging, then we will find we need to write functions for class to gurantee its safty. However, in python we can use @property to simply our call step. e.g.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Student(object):
    @property
    def score(self):
        return self._score

    @score.setter
    def score(self,value):
        if(value>100 or value<0):
            raise ValueError('score must between 0 to 100')
        self._score=value

a=Student()
a.score=99
print(a.score)

3.Multiple Inheritance

Python also supports multiple inheritance. And the way it goes is similar to inheritance in c++. Just add the inherited class in the parenthesis.

class Animal(object):
    pass

class Mammal(Animal):
    pass

class Bird(Animal):
    pass

class runnable(object):
    pass

class flyable(object):
    pass

class Dog(Mammal,flyable):
    pass

Also, we often use MixIn to represent this is a multi-inheritance.

4.costumizing class

In this secion, we will face with various in-built functions:
- init().
- str(). # support us to return a str when having defined a class.
- getitems(). # if we want to use index to get element in class, use this.
- iter(). # let the class have iteratable attribute which supports for loop.
- getattr(). # be called when explainer cannot find attribute in this class.
- call(). # let an object be an function that can be called without passing self argument.

Let’s look at an example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class fibonaci(object):
    def __init__(self):
        self.a,self.b=0,1

    def __iter__(self):
        return self

    def __next__(self):
        self.a,self.b=self.b,self.a+self.b
        if(self.a>1000):
            raise StopIteration()
        else:
            return self.a

    def __getitem__(self,n):
        if isinstance(n,slice):
            start=n.start
            stop=n.stop
            if start==None:
                start=0
            a,b=0,1
            L=[]
            for i in range(stop):
                a,b=b,a+b
                if i>=start:
                    L.append(a)
            return L
        if isinstance(n,int):
            a,b=0,1
            for i in range(n):
                a,b=b,a+b
            return a

    def __getattr__(self,attr):
        if attr=='age':
            return 99
        else:
            raise AttributeError('\'student\' object don\'t have \'%s\' attribute'% attr)

    def __call__(self):
        print('This is a fibonaci num')


a=fibonaci()
a()
print(a.age)
print(a.che)

5.enum

syntax:

from enum import Enum.  
Month=Enum('month',('Jan','Feb',..'Dec')).  

Through this, we define a enum, each instance in it is class type.

6.metaclass

(Leave one page to talk about it specially) This metaclass seems quite diffcult to understand :(

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值