• 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

  • 相关阅读:
    Thrift --- 支持双向通信
    Go -- 配置监控系统
    Go -- RPC 之 Thrift
    Go -- 一致性哈希算法
    Go -- runtime.Gosched()的作用分析
    Go -- import使用及. _的作用解析
    BNF 和 ABNF 扩充巴科斯范式 了解
    转 HTTP.SYS 详解
    转 HTTP/2: The Long-Awaited Sequel
    网站分析
  • 原文地址:https://www.cnblogs.com/Kingwjk/p/8007250.html
Copyright © 2020-2023  润新知