美文网首页
Python定义一个类

Python定义一个类

作者: 莫尛莫 | 来源:发表于2018-04-03 15:49 被阅读398次

    在面向对象的世界里,
    你的代码通常称为 类的方法 method
    而数据通常称为 类的属性 attribute
    实例化的数据对象通常称为 实例 instance

    Python使用class创建类。每个定义的类都有一个特殊的方法,名为__init__(),可以通过这个方法控制如何初始化对象。
    类中方法的定义与函数的定义类似,基本形式如下:

    class Athlete:
        def __init__(self):
            # The code to initialize a "Athlete" object.
    

    1. __init__()方法

    有了类之后,创建对象实例很容易。只需将对类名的调用赋至各个变量。通过这种方式,类(以及__init__()方法)提供了一种机制,允许你创建一个定制的工厂函数,用来根据需要创建多个对象实例。
    与C++系列语言不同,Python中没有定义构造函数new的概念。Python会对你完成对象构建,然后你可以使用__init__()方法定制对象的初始状态。

    2. self参数

    Python处理实例化a = Athlete()时,把工厂函数调用转换为了Athlete().__init__(a),也就是说,Python会将实例的目标标识符a赋至self参数中,这是一个非常重要的参数赋值。如果没有这个赋值,Python解释器无法得出方法调用要应用到哪个对象实例。
    注意:类代码设计为在所有对象实例间共享:方法是共享的,而属性不共享。self参数可以帮助标识要处理哪个对象实例的数据。
    每一个方法的第一个参数都是self

    class Athlete:
        def __init__(self, a_name, a_dob=None, a_times=[]):
            self.name = a_name
            self.dob = a_dob
            self.times = a_times
    
        def top3(self):
            return(sorted(set([sanitize(t) for t in self.times])) [0:3])
    
        def add_time(self, time_value):
            self.times.append(time_value)
    
        def add_times(self, list_of_times):
            self.times.extend(list_of_times)
    

    3. 继承

    可以继承list类创建AthleteList类,list类自带append()extend()方法

    class AthleteList(list):
        def __init__(self, a_name, a_dob=None, a_times=[]):
            list.__init__([])
            self.name = a_name
            self.dob = a_dob
            self.extend(a_times)
            
        def top3(self):
            return (sorted(set([sanitize(t) for t in self])) [0:3])
    

    4. 代码示例

    def sanitize(time_string):
        if '_' in time_string:
            splitter = '_'
        elif ':' in time_string:
            splitter = ':'
        else:
            return(time_string)
        (mins, secs) = time_string.split(splitter)
        return(mins + '.' + secs)
    
    class AthleteList(list):
        def __init__(self, a_name, a_dob=None, a_times=[]):
            list.__init__([])
            self.name = a_name
            self.dob = a_dob
            self.extend(a_times)
            
        def top3(self):
            return (sorted(set([sanitize(t) for t in self])) [0:3])
    
    def get_coach_data(filename):
        try:
            with open(filename) as f:
                data = f.readline()
            templ = data.strip().split(',')
            return (Athlete(templ.pop(0), templ.pop(0), templ))
        except IOError as ioerr:
            print('File error: ', + str(ioerr))
            return(None)
    
    james = get_coach_data('james2.txt')
    print(james.name + "'s fastest times are: " + str(james.top3()))
    

    相关文章

      网友评论

          本文标题:Python定义一个类

          本文链接:https://www.haomeiwen.com/subject/vvjicftx.html