think python 第17章 classes and methods

17.1object-oriented features

17.2printing objects

在16章中,定义了一个Time类,后续练习写了一个print_time函数。如果想调用这个函数,必须要给这个函数传递一个Time对象作为参数。如果要把print_time转换成方法,需要把函数定义转移到类定义里。

>>> class Time(object):
    def print_time(time):
        print("%.2d:%.2d:%.2d" % (time.hour,time.minute,time.second))

        
>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 0
>>> #现在有两种方式调用print_time。第一中是使用函数语法(不常见)
>>> Time.print_time(start)
09:45:00
>>> #另一种方法是使用方法语法
>>> start.print_time()
09:45:00
>>> #在这种方式里,print_time是方法名,start是方法被调用的对象,叫做主体。
>>> #习惯上,方法的第一个参数是self,所以更常见的写法是这样:
>>> class Time(object):
    def print_time(self):
        print("%.2d:%.2d:%.2d" % (self.hour,self.minute,self.second))

        

17.3another example

17.4a more complicated example

17.5the init method

 

posted on 2018-03-03 10:21  土间埋  阅读(193)  评论(0编辑  收藏  举报

导航