码迷,mamicode.com
首页 > 编程语言 > 详细

Python 面向对象的综合应用

时间:2018-03-22 19:18:03      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:first   ret   对象   UNC   color   def   erro   .sh   inner   

#   面向对象的综合应用
#   计算器:实现一些基本的计算操作,已经打印结果

#   --------------- 代码1  ----------------------
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def mulit(x, y):
    return x * y


print(add(2, 4))    #   6

#   实现   (2 + 4 - 3) * 5
res1 = add(2, 4)
res2 = subtract(res1, 3)
res3 = res2 * 5
print(res3) #   15

#   --------------- 代码2 -----------------------
class Caculator:
    __result = 0
    @classmethod
    #设置一个首数
    def first_value(cls, value):
        cls.__result = value

    @classmethod
    def add(cls, n):
        cls.__result +=  n
    @classmethod
    def subtract(cls, n):
       cls.__result -= n

    @classmethod
    def mulit(cls, n):
        cls.__result *= n

    @classmethod
    def show(cls):
        return cls.__result

Caculator.first_value(2)
Caculator.add(4)
Caculator.subtract(3)
Caculator.mulit(5)
print(Caculator.show()) #   15

#   --------------- 代码3 -----------------------
class Caculator:
    def __init__(self, firstNum):
        self.__result = firstNum

    def add(self, n):
        self.__result +=  n

    def subtract(self, n):
        self.__result -= n

    def mulit(self, n):
        self.__result *= n

    def show(self):
        return self.__result

c = Caculator(2)
c.add(4)
c.subtract(3)
c.mulit(5)
print(c.show()) #   15

#   --------------- 代码4 容错处理 -----------------------
class Caculator:
    def __check_num_zsq(func):
        def inner(self, n):
            if not isinstance(n, int):
                raise TypeError("数据类型错误")
            return func(self, n)
        return inner

    @__check_num_zsq
    def __init__(self, firstNum):
        self.__result = firstNum

    @__check_num_zsq
    def add(self, n):
        self.__result +=  n

    @__check_num_zsq
    def subtract(self, n):
        self.__result -= n

    @__check_num_zsq
    def mulit(self, n):
        self.__result *= n

    def show(self):
        return self.__result

c = Caculator(2)
c.add(4)
c.subtract(3)
c.mulit(5)
print(c.show()) #   15

 

Python 面向对象的综合应用

标签:first   ret   对象   UNC   color   def   erro   .sh   inner   

原文地址:https://www.cnblogs.com/delphiclub/p/8625378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!