1 頁 (共 1 頁)

#1 [分享] 在寫Class中...

發表於 : 2023年 1月 31日, 21:58
匿名 1
覺得python黑魔法真的讓人頭暈…… (例如: Metaclass, Closure......)


今天寫計算的Class

代碼: 選擇全部

"""this is a Caculate class

parameter must int or float
"""
class Caculate:
    """
    sum, sub, mult, div, root, pow must has 2 parameter (a, b)
    sqr, cub, spr, cur must have 1 parameter (a)
    """
    def __init__(self):
        print('lets caculate!')
    def sum(self, a, b):
        print(a+b)
    def sub(self, a, b):
        print(a-b)
    def mult(self, a, b):
        print(a*b)
    def div(self, a, b):
        try:
            print(a/b)
        except ZeroDivisionError:
            print('Divisor cannot be 0')
    def squ(self, a):
        print(a**2)
    def cub(self, a):
        print(a**3)
    def sqr(self, a):
        print(a**0.5)
    def cur(self, a):
        cubr = 1/3
        print(a**cubr)
    def root(self, a, b):        
        try:
            root_num = 1/b
            print(a**root_num)
        except ZeroDivisionError:
            print("Second parameter cannot be 0")
    def pow(self, a, b):
        if a == 0:
            if b != 0:
                try:
                    print(a**b)
                except ZeroDivisionError:
                    print('0 cannot be raised to a negative power')
            if b == 0:
                print(a**b)
                print("But Limit does not exist")
        else:
            print(a**b)
螢幕擷取畫面 2023-01-31 215414.png