class Bike: compose = ['frame','wheel','pedal'] def use(self): print('you are riding') my_bike = Bike() my_bike.use()输出:
you are riding
和函数 样,实例方法也是可以有参数的。
class Bike: compose = ['frame','wheel','pedal'] def use(self,time): print('you are {}m'.format(time*100)) my_bike = Bike() my_bike.use(10)输出:
you are 1000m
Python 类中有一些“魔法方法”,_init_() 方法就是其中之一。在我们创造 例的时候,不需要引用该方法 会被自动执行。
class Bike: compose = ['frame','wheel','pedal'] def __init__(self): self.other = 'basket' def use(self,time): print('you are {}m'.format(time*100)) my_bike = Bike() print(my_bike.other)