python 学习_第三模块 面向对象(中级)

1.组合

#
# 组合的使用
class People:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

class Teacher(People):
    def __init__(self,name,age,sex,level,salary):
        super().__init__(name,age,sex)
        self.level = level
        self.salary = salary
    def teach(self):
        print("%s is teaching" % self.name)

class Student(People):
    def __init__(self,name,age,sex,class_time):
        super().__init__(name,age,sex)
        self.class_time = class_time
    def learn(self):
        print("%s is learning " % self.name)

class School:
    def __init__(self,school_addr,school_name):
        self.school_addr = school_addr
        self.school_name = school_name
    def tell_info(self):
        print('学校名为 <%s>  学校地址为 <%s>' % (self.school_addr, self.school_name))

class Course:
    def __init__(self,course_name,course_price,course_period):
        self.course_name = course_name
        self.course_price = course_price
        self.course_period = course_period
    def tell_info(self):
        print('课程名<%s> 课程价钱<%s> 课程周期<%s>' % (self.course_name, self.course_price, self.course_period))

class Data:
    def __init__(self,year,mon,day):
        self.year = year
        self.mon = mon
        self.day = day
    def tell_info(self):
        print('%s-%s-%s' %(self.year,self.mon,self.day))

t = Teacher('alex',28,'man',10,3000)
py1 = Course('python','13000','3 month')
linux1 = Course('linux1','11000','2 month')
d = Data(2019,4,3)
s = Student('yangyang',18,'man','08:30:00')

s.birh=d
s.birh.tell_info()
# 2019-4-3

s.course=py1
s.course.tell_info()
# 课程名<python> 课程价钱<13000> 课程周期<3 month>

2.抽象类   接口继承

import abc

class Animal(metaclass=abc.ABCMeta): #只能被继承,不能被实例化
    all_type='animal'

    @abc.abstractmethod
    def run(self):
        pass

    @abc.abstractmethod
    def eat(self):
        pass

class People(Animal):
    def run(self):
        print('people is running')

    def eat(self):
        print('people is eating')

class Pig(Animal):
    def run(self):
        print('people is walking')

    def eat(self):
        print('people is eating')

3.多态

#多态:同一类事物的多种形态
import abc
class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
    @abc.abstractmethod
    def talk(self):
        pass

class People(Animal): #动物的形态之一:人
    def talk(self):
        print('say hello')

class Dog(Animal): #动物的形态之二:狗
    def talk(self):
        print('say wangwang')

class Pig(Animal): #动物的形态之三:猪
    def talk(self):
        print('say aoao')

class Cat(Animal):
    def talk(self):
        print('say miamiao')

#多态性:指的是可以在不考虑对象的类型的情况下而直接使用对象
peo1=People()
dog1=Dog()
pig1=Pig()
cat1=Cat()

# peo1.talk()
# dog1.talk()
# pig1.talk()

def func(animal):
    animal.talk()


func(peo1)
func(pig1)
func(dog1)
func(cat1)

4.封装

封装的意义:
1. 封装数据属性: 明确的区分内外,控制外部对隐藏属性的操作
2. 隔离复杂度
# 1.封装数据属性
class People:
    def __init__(self,name,age):
        self.__name = name
        self.__age = age

    def tell_info(self):
        print('Name:<%s> Age:<%s>' %(self.__name,self.__age))

    def set_info(self,name,age):
        if not isinstance(name,str):
            print('名字必须是字符串类型')
            return
        if not isinstance(age,int):
            print('年龄必须是数字类型')
            return
        self.__name = name
        self.__age = age

p = People('alex' ,11)
p.tell_info()
p.set_info('egon','1')
p.tell_info()
# 2封装方法:隔离复杂度
class ATM:
    def __card(self):
        print('插卡')
    def __auth(self):
        print('用户认证')
    def __input(self):
        print('输入取款金额')
    def __print_bill(self):
        print('打印账单')
    def __take_money(self):
        print('取款')

    def withdraw(self):
        self.__card()
        self.__auth()
        self.__input()
        self.__print_bill()
        self.__take_money()

a = ATM()
a.withdraw()

''' 封装的扩展性'''

5.property
# 1.property 使用
class People:
    def __init__(self,name,weigth,height):
        self.name = name
        self.weigth = weigth
        self.height = height

    @property
    def bmi(self):
        return  self.weigth/(self.height **2)

p = People('yy',67,1.78)
print(p.bmi)
# 2. property 使用
class People:
    def __init__(self,name):
        self.__name = name

    @property
    def name(self):
        return  self.__name

    @name.setter
    def name(self,val):
        if not isinstance(val,str):
            print('名字必须是字符串类型')
            return
        self.__name = val

    @name.deleter
    def name(self):
        print('deleter')
        print('不允许删除')

p = People('yy')
# print(p.name)
# p.name = 'august'
# print(p.name)
del p.name

6.绑定方法

'''
在类内部定义的函数分为两大类:
    一: 绑定方法: 绑定给谁,就应该由谁来调用。 谁来调用就会把调用者当着第一个参数自动传入

            绑定到对象的方法:  在类定义的没有被任何装饰器修饰的

            绑定到类的方法:    在类内定义的被装饰器classmethod 修饰的方法


    二: 非绑定方法: staticmethod  没有自动传值 这么一说,就是类中定义的一个普通工具   对象和类都可以使用
            非绑定方法:  不与类或者对象绑定

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

    def tell(self):
        print('名字是%s '% self.name)

    @classmethod
    def func(cls):
        print(cls)

    @staticmethod
    def func1(x,y):
        print(x+y)

f = Foo('egon')
# Foo.func()
# print(f.tell())
Foo.func1(1,2)
f.func1(1,2)
import settings
import hashlib
import  time

class People:
    def __init__(self,name,age,sex):
        self.id = self.create_id()
        self.name = name
        self.age = age
        self.sex = sex

    def tell_info(self):
        print('Name:%s Age:%s Sex:%s' %(self.name,self.age,self.sex))

    @classmethod
    def from_conf(cls):
        obj = cls(settings.name,settings.age,settings.sex)
        return  obj

    @staticmethod
    def create_id():
        m = hashlib.md5(str(time.time()).encode('utf-8'))
        return  m.hexdigest()


p=People('egon',18,'male')
#绑定给对象,就应该由对象来调用,自动将对象本身当作第一个参数传入
p.tell_info()

#绑定给类,就应该由类来调用,自动将类本身当作第一个参数传入
p = People.from_conf()
p.tell_info()


#非绑定方法,不与类或者对象绑定,谁都可以调用,没有自动传值一说
p1=People('egon1',18,'male')
p2=People('egon2',28,'male')

print(p1.id)

7.反射

#hasattr()

'''
    Return whether the object has an attribute with the given name.
    返回对象是否具有给定名称的属性。
    This is done by calling getattr(obj, name) and catching AttributeError.
    这是通过调用GETAutr(Objo,name)和捕获属性错误来完成的。
'''

#getattr()
'''
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
'''

#setattr()
"""
Sets the named attribute on the given object to the specified value.

setattr(x, 'y', v) is equivalent to ``x.y = v''
"""

#delattr()
"""
Deletes the named attribute from the given object.

delattr(x, 'y') is equivalent to ``del x.y''
"""

反射的应用

class People:
    country = 'china'

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

    def talk(self):
        print('%s is talking' % self.name)

obj=People('egon',18)
# print(obj.name)
# print(obj.talk)

# hasattr
print(hasattr(obj,'name')) #obj.name #obj.__dict__['name']
print(hasattr(obj,'talk'))


# getattr
print(getattr(obj,'namexxx',None))
print(getattr(obj,'talk',None))

# setattr
setattr(obj,'sex','male')
print(obj.sex)


# delattr
delattr(obj,'age')
print(obj.__dict__)


# 反射的作用
class  Service:
    def run(self):
        while True:
            inp = input('>>>  ').strip()
            cmds = inp.split()

            if hasattr(self,cmds[0]):
                func = getattr(self,cmds[0])
                func(cmds)

    def get(self,cmds):
        print('get.......',cmds)

    def put(self,cmds):
        print('put.......',cmds)

obj = Service()
obj.run()
原文地址:https://www.cnblogs.com/augustyang/p/10650439.html