• python __str__ & __repr__ & __cmp__


    For ( __str__ ),we going to see a example ...

    and find who is working for ...

    #!/usr/bin/python
    
    class Person(object):
        
        def __init__(self,name,gender):
            self.name = name
            self.gender = gender
    
    if __name__ == '__main__':
        
        p = Person('Frank',23)
        print p

    See,The instance of ( Person ) have a default method ,just like ( describe method ) ...

    it's called by instance self (here,is p itself) ...

    So,what it is name ...

    keep read,you will find what's it is ...

    #!/usr/bin/python
    
    class Person(object):
        
        def __init__(self,name,gender):
            self.name = name
            self.gender = gender
        
        def __str__(self):
           """override the object method"""
            return 'Person object: %s,%d' % (self.name,self.gender)
    
    if __name__ == '__main__':
        
        p = Person('Frank',23)
        print p

    See,we got a totally different result ...

    So,we know who is the method ( __str__ ) ...

    Okay,next we will talk (__cmp__) inside method ...

    #!/usr/bin/python
    
    class Student(object):
    
        def __init__(self,name,score):
            self.name = name
            self.score = score
    
        def __str__(self):
            return '(%s: %s)' % (self.name,self.score)
    
        __repr__ = __str__
    
        def __cmp__(self,s):
            if self.score > s.score:
                return -1
    
            elif self.score < s.score:
                return 1
    
            else:
                if self.name < s.score:
                    return -1
                elif self.name < s.name:
                    return 1
                else:
                    return 0
    
    if __name__ == '__main__':
        L = [Student('Tim',99),Student('Bob',88),Student('Alice',99)]
        print sorted(L)

    Can we drop this masquerade
  • 相关阅读:
    4header组件开发
    3组件骨架开发
    2项目目录设计
    1项目相关的一些简介
    21AJax与Comet
    20JSON
    获取特定筛选条件下数据的四分位点
    动态长度字符串的解析拆分问题
    myBase Desktop 7无限免费试用方法
    VBA 将Excel工作簿中所有表格进行一键排版
  • 原文地址:https://www.cnblogs.com/landpack/p/4605579.html
Copyright © 2020-2023  润新知