马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class Tickets:
normal_adult = 100
weekd_adult = 120
normal_child = 50
weekd_child = 60
def cal(num_adult, num_child, weekend):
if weekend == 0:
print('%d 个成人 + %d 个小孩周末票价为:%.2f' % (num_adult, num_child, num_adult * normal_adult + num_child * normal_child))
else:
print('%d 个成人 + %d 个小孩平日票价为:%.2f' % (num_adult, num_child,num_adult * weekd_adult + num_child * weekd_child))
a = Tickets()
weekend = 0
num_adult = 2
num_child = 1
a.cal(num_adult, num_child, weekend)
####a.cal(num_adult, num_child, weekend)
TypeError: cal() takes 3 positional arguments but 4 were given
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。
class Tickets:
normal_adult = 100
weekd_adult = 120
normal_child = 50
weekd_child = 60
def cal(self, num_adult, num_child, weekend):
if weekend == 0:
print('%d 个成人 + %d 个小孩周末票价为:%.2f' % (num_adult, num_child, num_adult * self.normal_adult + num_child * self.normal_child))
else:
print('%d 个成人 + %d 个小孩平日票价为:%.2f' % (num_adult, num_child,num_adult * weekd_adult + num_child * weekd_child))
a = Tickets()
weekend = 0
num_adult = 2
num_child = 1
a.cal(num_adult, num_child, weekend)
|