p134-

#练习:基于圆形类实现一个环类,接受参数为大圆R和小圆半径r
#实现方法:计算环形面积和环形周长
#借助组合,要求组合圆形类的对象完成需求
from math import pi

class Circle:
    def __init__(self,r):
        self.r=r
    def area(self):
        return self.r**2*pi
    def perimeter(self):
        return 2*pi*self.r

class Ring:
    def __init__(self,r1,r2):
        # 传递半径大小的顺序的问题
        r1,r2 = (r1,r2)if r1>r2 else (r2,r1) #在初始化的时候就确定r1一定要大于r2
        self.circle1 = Circle(r1) #Ring的变量就是一个圆
        self.circle2 = Circle(r2)

    def area(self):
        return self.circle1.area()-self.circle2.area()
    def perimeter(self):
        return self.circle1.perimeter()+self.circle2.perimeter() #周长是内外2个圆的周长和

r=Ring(5,10) # 这里的结果和 Ring(10,5)效果一样
print(r.area()) #235.61944901923448
print(r.perimeter()) #94.24777960769379
#为什么要用类的组合(和后续的类的继承区分开)
#圆环用到了圆的类,两个类都用到了pi,如果pi以后直接用3.14 ,那么就要全部改。代码重复率越少,代码维护的成本就越小
#练习 【未完】
#员工信息表
#有一个文件,文件存储格式如下
# id,name,age,phone,job
#1、tom,22,1383838388,IT
#2、jerry,21,1563838388,Teacher
#3、eric,23,1443838388,Student

#查询
# select 查询这个文件
# select name,age where age>20
# select age,name,job where age >20
# select age,name,job where age=20
# select age,name,job where name='tom'
# select age,name,job where job='IT'
# select age,name,job where phone like '133'

#增删改
#创建员工记录,id 要顺序增加 insert
#可删除指定员工记录,直接输入员工id即可 delete
#修改员工信息 set 列名=’新值‘ where 条件 (先用where 查找,再用set修改)
#
#操作员工信息表必须先登录,登录认证用装饰器完成,其他需求尽量用函数完成
#计算算术表达式中的乘除法
import re
def div_mul(str): #乘除法
    if '*' in str:
        a,b = str.split('*')
        return float(a)*float(b)
    elif '/' in str:
        a,b = str.split('/')
        return float(a)/float(b)

def sub_pul(str):#加减
    if '+' in str:
        a,b = str.split('+')
        return float(a)+float(b)
    elif '-' in str:
        a,b = str.split('-')
        return float(a)-float(b)

# exp = '(-1*(3-4))*6-((-3)+4*(-5+8))/2'

#先乘除后加减
def calc(exp):
    while True: #先乘除
        ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp)
        if ret:
            new_exp = ret.group()
            result = div_mul(ret.group())
            exp = exp.replace(new_exp,str(result))
        else:
            break

    while True: #后加减
        ret = re.search('\d+(\.\d+)?[+-]-?\d+(\.\d+)?',exp)
        if ret:
            new_exp = ret.group()
            result = sub_pul(ret.group())
            exp = exp.replace(new_exp,str(result))
        else:
            break

    return exp
#去除多个加减号相连
def remove_addsub(exp):
    while re.findall('[-+]{2,}',exp):
        exp = exp.replace('+-','-')
        exp = exp.replace('-+','-')
        exp = exp.replace('--','+')
        exp = exp.replace('++','+')
    return exp

#去括号【未完】
def remove_parentheses(exp):
    pass
#面向对象三大特性:继承 封装 多态
class Cat:
    def __init__(self,name):self.name = name
    def eat(self):print(f'{self.name} eat')
    def sleep(self):print(f'{self.name} sleep')
    def climb_tree(self):print(f'{self.name} climb tree')

class Dog:
    def __init__(self, name): self.name = name
    def eat(self): print(f'{self.name} eat')
    def sleep(self): print(f'{self.name} sleep')
    def mind_house(self):print(f'{self.name} mind house')

cat1 = Cat('tom')
cat1.eat()  #tom eat
cat1.sleep() #tom sleep
cat1.climb_tree() #tom climb tree

dog1 = Dog('jerry')
dog1.eat()  #jerry eat
dog1.sleep() #jerry eat
dog1.mind_house() #jerry mind house
#代码重复,把相同的方法封装在父类Animal中
#变更一下
class Animal:
    count_eye = 2
    def __init__(self, name): self.name = name
    def eat(self): print(f'{self.name} eat')
    def sleep(self): print(f'{self.name} sleep')
class Cat(Animal):
    def climb_tree(self): print(f'{self.name} climb tree')
class Dog(Animal):
    def mind_house(self): print(f'{self.name} mind house')

#得到同样的结果
cat1 = Cat('tom')
cat1.eat()  #tom eat
cat1.sleep() #tom sleep
cat1.climb_tree() #tom climb tree
print(cat1.count_eye) #2 子类 直接使用父类的方法和静态变量

dog1 = Dog('jerry')
dog1.eat()  #jerry eat
dog1.sleep() #jerry eat
dog1.mind_house() #jerry mind house
print(dog1.count_eye) #2
#继承语法
# class 父类:
# class 子类名(父类名):
#子类直接使用父类中的方法和静态变量
#实例化一个对象,先开辟一个新空间,空间有一个类对象指针,指向子类,子类中有一个类指针,指向父类
#方法重载
class Animal:
    def __init__(self, name): self.name = name
    def eat(self): print(f'{self.name} eat')
    def sleep(self): print(f'{self.name} sleep')
class Cat(Animal):
    def eat(self): print(f'{self.name} eat cat food') #猫吃猫粮
    def climb_tree(self): print(f'{self.name} climb tree')
class Dog(Animal):
    def eat(self): print(f'{self.name} eat dog food') #狗吃狗粮
    def mind_house(self): print(f'{self.name} mind house')

cat1 = Cat('tom')
cat1.eat()  #tom eat cat food

dog1 = Dog('jerry')
dog1.eat()  #jerry eat dog food
#如果执行了子类的同事又想同时执行父类,比如猫吃了猫粮,同时调用Animal里的eat
#再如果爬树的过程中睡了一会 sleep
class Cat(Animal):
    def eat(self):
        print(f'{self.name} eat cat food')
        Animal.eat(self) #这里用 ’父类名.方法(self)‘ 的方式调用,因为本身有eat()方法,会先调用自己的
    def climb_tree(self):
        print(f'{self.name} climb tree')
        self.sleep() #这里直接用self.sleep() 调用父类,因为子类本身没有sleep()方法 ,就不会歧义
#写结果
class Foo:
    def __init__(self):
        self.func()
    def func(self):
        print('in foo')
class son(Foo):
    def func(self):
        print('in son')
son() # in son  先调用子类方法
#给猫 和 狗 定制个性属性
class Animal:
    def __init__(self, name): self.name = name
    def eat(self): print(f'{self.name} eat')
    def sleep(self): print(f'{self.name} sleep')
class Cat(Animal):
    def __init__(self, name,eye_color):
        Animal.__init__(self,name) # 把父类的init方法先执行
        self.eye_color = eye_color #在创建个性化属性  眼镜颜色
    def eat(self): print(f'{self.name} eat cat food') #猫吃猫粮
    def climb_tree(self): print(f'{self.name} climb tree')
class Dog(Animal):
    def __init__(self, name,size):
        Animal.__init__(self,name)
        self.size =size #体型
    def eat(self): print(f'{self.name} eat dog food') #狗吃狗粮
    def mind_house(self): print(f'{self.name} mind house')

c1 = Cat('tom','brown')
print(c1.eye_color)

d1 = Dog('jerry','big')
print(d1.size)
#单继承 ,自下而上寻找方法去执行
#多继承,先继承谁就先调用谁,如果只有1个父类有相应的方法,就调用这个方法
class A:
    def func(self):print('A func')
class B:
    def func(self):print('B func')
class C(A,B):pass
C().func() #A func
#object  类 是类祖宗,所有python3 中的类都继承object类
#type 和 isinstance
class Animal(object):pass
class Cat(Animal):pass
c1 = Cat()

print(type(c1) is Cat) #True
print(type(c1) is Animal) #False  #type 不能判断类的继承

print(isinstance(c1,Cat)) #True
print(isinstance(c1,Animal)) #True #isinstance 可以判断类的继承
#FunctionType 和 MethodType  函数 和 绑定方法
from types import FunctionType,MethodType
class A(object):
    def func(self):print('func')
print(A.func) #<function A.func at 0x000001902EBA4F70>  #用类名调用指的是函数
a=A()
print(a.func) #<bound method A.func of <__main__.A object at 0x000001902EBD4C70>> 用对象名调用指的是方法

print(isinstance(A.func,FunctionType)) #True
print(isinstance(A.func,MethodType)) #False
print(isinstance(a.func,FunctionType)) #False
print(isinstance(a.func,MethodType)) #True
#类属性补充
class A(object):
    '''
    这个类是测试用的
    '''
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def func(self):pass
print(A.__name__) # A   #类名
print(A.__doc__) # 这个类是测试用的  #注释
print(A.__base__) #<class 'object'>  #基类
print(A.__bases__) #(<class 'object'>,)  #所有父类组成的元组
print(A.__dict__) # {'__module__': '__main__', 。。。。。#字典属性
print(A.__module__) # __main__ #所属模块
#对象可以保存在文件中,比如游戏中,人物角色,状态装备等,退出游戏就可以保存
import pickle
class Player(object):
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex
        self.blood=100
        self.weapon = '大刀'
p1 = Player('tom','male')
print(p1.__dict__) #{'name': 'tom', 'sex': 'male', 'blood': 100, 'weapon': '大刀'}
with open('player.info',mode='wb') as f1:
    pickle.dump(p1,f1)
with open('player.info',mode='rb') as f1:
    obj = pickle.load(f1)
    print(obj.name) #tom
    print(obj.blood) #100
    print(obj.weapon) #大刀
posted on 2020-08-01 22:34  94小渣渣  阅读(128)  评论(0编辑  收藏  举报