python中如何调用类的方法

2022-06-21 08:58:15

python中如何调用类的方法

类的方法的调用:

与普通的函数调用类似

1、类的内部调用:self.<方法名>(参数列表)。

2、在类的外部调用:<实例名>.<方法名>(参数列表)。

注意:以上两种调用方法中,提供的参数列表中都不用包括self。

演示一个类:

classWasher:def__init__(self):
        self.water=0
        self.scour=0defadd_water(self,water):print('Add water:',water)
        self.water= waterdefadd_scour(self,scour):
        self.scour= scourprint('Add scour:',self.scour)defstart_wash(self):print('Start wash...')if __name__=='__main__':
    w= Washer()
    w.add_water(10)
    w.add_scour(2)
    w.start_wash()

运行结果

Add water: 10
Add scour: 2
Start wash...
  • 作者:朝斯~夕斯
  • 原文链接:https://blog.csdn.net/qq_45810826/article/details/120629652
    更新时间:2022-06-21 08:58:15