2020-10-03

    科技2022-07-12  131

    class C: def myFun(): print(“hello!”) c = C() c.myFun() 此段程序的错误在于myFun()方法中没有传入self参数。 2.票价计算

    // A code block // An highlighted block class ticketprice(): def __init__(self, workday=True, adult=True): self.price = 100 if workday: self.ratio = 1 else: self.ratio = 1.2 if adult: self.discount = 1 else: self.discount = 0.5 def get_price(self): return int(self.price*self.ratio*self.discount)adult1 = ticketprice(workday=True, adult=True).get_price()adult2 = ticketprice(workday=True,adult=True).get_price()child1 = ticketprice(workday=True,adult=False).get_price()totalprice=adult1+adult2+child1print("2位成人和1个小孩平日票价为:%.2f"%totalprice)

    魔法方法__init__ init__是一个构造函数,这个函数默认是没有参数的,如果我们需要给类的实例的属性初始化一些值,这是就要用到__init__函数了。 魔法方法__new __new__的主要作用是当我们需要继承一些不可变的class时(如str,tuple,int),提供给你一个自定义这些类的实例化的过程。

    // A code block class Capstr(str): def __new__(cls,string): string = string,upper()#此处的两个string是不同的,后者是传进来的参数 return str.__new__(cls,string) a = Capstr("I love cuiyue") print(a)# I LOVE CUIYUE

    魔法方法__del__ 此方法相当于析构函数,当没有任何变量引用此类的时候,__del__方法才会把它销毁。

    // A code block class a(): def __init__(self) print("我是__init__方法,我被调用了") def __del__(self) print("我是__del__方法,我被调用了") a0 = a() #调用__init__方法 a1 = a0 #不调用__init__方法 a2 = a1 del a2 del a1 #不调用__del__方法 del a0 #只有这次del方法才会调用__del__方法
    Processed: 0.013, SQL: 8