面向对象笔记。

面向对象:

  类:抽象概念,类型。用来描述具有相同的属性和方法的对象的集合。定义了该集合中每个对象所共有的属性和方法,对象是类的实例。

  类变量:在整个实例化的对象中是公用的。类变量 定义在类中且在函数体之外。

  实例变量:在类的声明中,属性是用变量来表示的。这种变量被称为实例变量。

  实例化:创建一个类的实例,类的具体对象。

class Student(object): #类属性:类名,属性名。
    count = 0
    def __init__(self,score):#----》构造函数:实例化对象时自动调用的
        #self:当前对象
        self.score = score
        Student.count += 1
    #实例方法
    def setName(self,name):
        if 1<len(name)<32:
            self.name = name
            return  True
         else:
            reeturn False

#实例化对象
s1 = Student()
#访问对象的属性
print(s1.score)
s1.name = 'ssss'
print(s1.name)
def __del__(self): #析构方法:对象销毁时自动调用。
    print('..........')  
#私有方法
def __privateFun(self):
    print('........')
# 私有属性---》解释器做了名字的修改
print(s1.__Student__score)

#私有方法
s1.__Student__prinvate

继承:

  1,如果在子类中需要父类的构造方法就需要显示的调用父类的构造方法,或者重写父类的构造方法

  2,在调用基类的方法时,需要加上父类的类名前缀,且需要带上self参数变量。

  3,python总是首先查找对应类型的方法,如果不能在派生类中找到对应的方法,他才开始到基类中逐个查找。

class Animal(object):
    def __init__(self,name,age=1,color='yellow'):
        self.name = name
        self.age = age
        self.__color = color #_Animal__color
    def show(self):
        print(self.name,self.age,self.__color)

class Dog(Animal):
    def __init__(self,name,age,breed):
        #调用父类方法
        #Animal.__init__(self,name,age)
        #super().__init__(name,age)
        super().__init__(name,age)
        self.breed = breed
    
    def show(self):
        Animal.show(self)
        print('.......')

animal = Animal(‘22’)
animal.show()#调用父类方法
d1 = Dog('.......')
d1.show()#调用子类
# 子类中不能直接访问继承的私有属性。

多继承:

  python 支持,但不建议使用

class A(object):
    def run(self):
        print('run A run')

class B(A):
    def run(self):
        super().run()
        print('run B run')

class C(A):
    def run(self):
        super().run()
        print('run C run')

class D(B, C):
    pass


c = C()
c.run()
# 获取类或者对象的方法和属性
print(dir(C))
# 获取类的继承顺序
print(C.__mro__)

d = D()
d.run()
print(D.__mro__)

多态

class Animal(object):
    def run(self):
        print('animal is running')


class Dog(Animal):
    def run(self):
        print('Dog run fast')


class Rabbit(Animal):
    def run(self):
        print('Rabbit jump...')

class Cat(Animal):
    pass

class Timer(object):
    def run(self):
        print('the time is running')


# 多态:同一种类型,不同的表现形式
def runTwice(animal):
    animal.run()
    animal.run()

a = Animal()
rabbit = Rabbit()

runTwice(a)
runTwice(rabbit)

# 鸭子类型
tm = Timer()
runTwice(tm)

 限制实例 属性

class Person(object)
    __slots__ = ('name','age')#只允许有‘name’ ‘age’属性
per1 = Person()
per1.name = '....'
print(per1.name)
per1.height = .... #不允许

class Student(object):
    def __init__(self,age):
        if 0<=score<=100:
            self.__score=score
            return 'ok'
        else:
            return 'error'
    def getScore(self):
        return self.__score

    @property#访问器,可以单独存在
    def score(self):
        print('getter is called')
        return self.__score
    @score.setter #设置器,不单独存在,一定要有property
    def score(self,score):
        print('setter is called')
        if 0 <=score<=100:
            self.__score = score
            return 'ok'
        else:
            return 'error'
    @ property
    def age(self):
        return self.__age
s1 = Student(20)
'''
if s1.setScore(10) == 'ok': # s1.score= 100
    print(s1.getScore())
'''
s1.score = 100
print(s1.score)
print(s1.age)

设置器与访问器的作用:

  1,隐藏了实例变量

  2,控制实例变量的读写

  3,做正确性检验。

python魔法方法

class Student(object):
    def __init__(self,name = 'python'):
        '''创建类和属性时自动调用'''
        self.__name = name
    def __str__(self):
        '''打印本类对象时,自动调用'''
        return '........'
    def __repr__(self):
        '''在解释器环境下直接输出本对象,自动调用的方法'''
    return self.__str__()
    def __len__(self):
        '''调用len函数的时候自动调用的方法'''
        return 100
    def__call__(self):
        '''调用本类对象的时候自动调用的方法'''
        print('Student object name:%s' %self.__name)

print(dir(Student))
s = Student()
print(len(s))
s()


类名.__mro__#类的继承顺序

__dir__(类名或对象)#查看所有方法和属性

另一种构建类的方法,是先构建元类,以元类为模板构建类
class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        '''类方法'''
        attrs['add'] = lambda self, value : self.append(value)
        return type.__new__(cls, name, bases, attrs)

class Mylist(list, metaclass=ListMetaclass):
    pass

l = Mylist()
print(type(l))
l.add(1)
l.add('hello')
print(l)

猜你喜欢

转载自www.cnblogs.com/zhaojihua/p/10133676.html