zoukankan      html  css  js  c++  java
  • Python零散函数

     

    1. python json.dumps() json.dump()的区别

      注意cat ,是直接输出文件的内容

      load和loads都是实现“反序列化”,区别在于(以Python为例):

    • loads针对内存对象,即将Python内置数据序列化为字串

      如使用json.dumps序列化的对象d_json=json.dumps({'a':1, 'b':2}),在这里d_json是一个字串'{"b": 2, "a": 1}'

      d=json.loads(d_json)  #{ b": 2, "a": 1},使用load重新反序列化为dict

    • load针对文件句柄

      如本地有一个json文件a.json则可以d=json.load(open('a.json'))

      相应的,dump就是将内置类型序列化为json对象后写入文件

    2. sorted和sort

      sorted(iterable, cmp=None, key=None, reverse=False)

      

    3. 请定义Person类的__init__方法,除了接受 name、gender 和 birth 外,还可接受任意关键字参数,并把他们都作为属性赋值给实例。

    class Person(object):
        def __init__(self,name,gender,birth,**kw):
            self.name = name
            self.gender = gender
            self.birth = birth
            for key,value in kw.items():
                setattr(self,key,value)
            
    
    xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')
    
    print xiaoming.name
    print xiaoming.job

    34 请给 Person 类添加一个类属性 count,每创建一个实例,count 属性就加 1,这样就可以统计出一共创建了多少个 Person 的实例。

    class Person(object):
        count = 0
        def __init__(self,name):
            self.name = name
            Person.count += 1
            
    
    p1 = Person('Bob')
    print Person.count
    
    p2 = Person('Alice')
    print Person.count
    
    p3 = Person('Tim')
    print Person.count

    5. 类的私有变量不可以直接获取,但可以用方法实例或者类私有方法获取

    # 通过实例的方法获取
    class Person(object):
        __count = 0
        def __init__(self,name):
            self.name = name
            Person.__count += 1 
    
        def get_count(self):
            return Person.__count
    
    p1 = Person('Alice')
    p2 = Person('Tom')
    
    print p1.get_count()
    # => 2
    
    # 通过类私有方法获取
    class Person(object):
        __count = 0
        def __init__(self,name):
            self.name = name
            Person.__count += 1 
    
        @classmethod
        def get_count(self):
            return self.__count
    
    p1 = Person('Alice')
    p2 = Person('Tom')
    
    print Person.get_count()
    # => 2

     6. 类的继承和组合

      每个类的定义都需要继承,没有的话,就从object继承

      6.1 组合:has关系

      6.2 继承:is关系

        示例:

    class Person(object):
        def __init__(self, name, gender):
            self.name = name
            self.gender = gender
    
    class Teacher(Person):
        def __init__(self, name, gender, course):
            super(Teacher,self).__init__(name,gender)
    #或者Person.__init__(self,name,gender)
            self.course = course

    7. python中多态

    类具有继承关系,并且子类类型可以向上转型看做父类类型,如果我们从 Person 派生出 Student和Teacher ,并都写了一个 whoAmI() 方法:

    class Person(object):
        def __init__(self, name, gender):
            self.name = name
            self.gender = gender
        def whoAmI(self):
            return 'I am a Person, my name is %s' % self.name
    
    class Student(Person):
        def __init__(self, name, gender, score):
            super(Student, self).__init__(name, gender)
            self.score = score
        def whoAmI(self):
            return 'I am a Student, my name is %s' % self.name
    
    class Teacher(Person):
        def __init__(self, name, gender, course):
            super(Teacher, self).__init__(name, gender)
            self.course = course
        def whoAmI(self):
            return 'I am a Teacher, my name is %s' % self.name

    在一个函数中,如果我们接收一个变量 x,则无论该 x 是 Person、Student还是 Teacher,都可以正确打印出结果:

    def who_am_i(x):
        print x.whoAmI()
    
    p = Person('Tim', 'Male')
    s = Student('Bob', 'Male', 88)
    t = Teacher('Alice', 'Female', 'English')
    
    who_am_i(p)
    who_am_i(s)
    who_am_i(t)
    运行结果:
    
    I am a Person, my name is Tim
    I am a Student, my name is Bob
    I am a Teacher, my name is Alice

    这种行为称为多态。也就是说,方法调用将作用在 x 的实际类型上。s 是Student类型,它实际上拥有自己的 whoAmI()方法以及从 Person继承的 whoAmI方法,但调用 s.whoAmI()总是先查找它自身的定义,如果没有定义,则顺着继承链向上查找,直到在某个父类中找到为止。

    由于Python是动态语言,所以,传递给函数 who_am_i(x)的参数 x 不一定是 Person 或 Person 的子类型。任何数据类型的实例都可以,只要它有一个whoAmI()的方法即可:

    class Book(object):
        def whoAmI(self):
            return 'I am a book'

    这是动态语言和静态语言(例如Java)最大的差别之一。动态语言调用实例方法,不检查类型,只要方法存在,参数正确,就可以调用。

    任务

    Python提供了open()函数来打开一个磁盘文件,并返回 File 对象。File对象有一个read()方法可以读取文件内容:

    例如,从文件读取内容并解析为JSON结果:

    import json
    f = open('/path/to/file.json', 'r')
    print json.load(f)

    由于Python的动态特性,json.load()并不一定要从一个File对象读取内容。任何对象,只要有read()方法,就称为File-like Object,都可以传给json.load()。

    请尝试编写一个File-like Object,把一个字符串 r'["Tim", "Bob", "Alice"]'包装成 File-like Object 并由 json.load() 解析。

    import json
    
    class Students(object):
        def read(self):
            return '["Tim", "Bob", "Alice"]'
    
    s = Students()
    
    print json.load(s)

    8. python 类的特殊方法

     需要说明的是,对于单纯的数字可以用内建的cmp()函数进行sorted()

    但如果不是单纯数字或者不是单纯字母,我们就需要自己定义__cmp__()

    定义的__cmp__() 函数里面,可以使用cmp()进行优选排序,cmp()是升序,-cmp()是降序

    示例

    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 cmp(self.name,s.name)
            return -cmp(self.score,s.score)
    
    L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
    print sorted(L)
    
    
    #返回结果:[(Alice: 99), (Tim: 99), (Bob: 88)]

      还有一个__format__,可以见 python cook 第八章 P231,自己定义日期格式

    根据书上,做的小练习

    _formats = {'default':'{self.d1}-{self.d2}-{self.d3}'}
    
    class Phone(object):
        """docstring for Phone"""
        def __init__(self, Phone):
            self.d1 = Phone[0:3]
            self.d2 = Phone[3:7]
            self.d3 = Phone[7:11]
        def __format__(self,code):
            if code == '':
                code = 'default'
            fmt = _formats[code]
            return fmt.format(self=self)
    
    s = Phone('18905055903')
    print format(s)

     类的@property 

    原文地址:http://www.imooc.com/code/6255

    @property---这是关键字,固定格式,能让方法当“属性”用。

    @score.setter---前面的"score"是@property紧跟的下面定义的那个方法的名字,"setter"是关键字,这种“@+方法名字+点+setter”是个固定格式与@property搭配使用。

     使用@property 后 再使用@属性.setter,可以对该属性的值进行约束

    如果有@property ,但是没有设置@属性.setter,那么这个属性只读,不可改

      练习 

    class Student(object):
    
        def __init__(self, name, score):
            self.name = name
            self.__score = score
            
    
        @property
        def score(self):
            return self.__score
    
        @score.setter
        def score(self, score):
            if score < 0 or score > 100:
                raise ValueError('invalid score')
            self.__score = score
    
        @property
        def grade(self):
            if self.score >= 80:
                return 'A'
            if self.score <60:
                return 'C'
            return 'B'
    
    s = Student('Bob', 59)
    print s.grade
    
    s.score = 60
    print s.grade
    
    s.score = 99
    print s.grade

     __slots__  允许存在的属性

    原文:http://www.imooc.com/code/6256

    注意:__slots__ 只对当前类起作用,子类中如果也要限制属性,也要自己定义__slots__,子类中定义自己要另外允许的属性即可

     1. 父类__slots__ = ('name', 'gender'),子类无__slots__ 

      那么:父类只能有'name', 'gender' 两个属性,子类属性无限制

    2. 父类__slots__ = ('name', 'gender'),子类__slots__ = 'age'

      那么:父类只能有'name', 'gender' 两个属性,子类只能有'name', 'gender' ,‘age’ 三个属性

    给类中的变量属性执行类型检查或者合法性验证

    @proterty

    Python cook P237

    对super的理解:

    1. Python: 你不知道的 super

    2. python cook P241

    类变量和实例变量

    python的类变量与实例变量以及__dict__属性

    变量查找的顺序:instance.__dict__ -> class.__dict__ -> baseclass.__dict__

    类里的类方法、实例方法和静态方法

    python 静态方法和类方法

    函数和方法的区别

    函数(function):

    1. 在外部def 定义的函数

    2. 类内部定义的静态方法@staticmethod

    方法(method):类里才有

    1. @classmethod 定义的函数,第一个参数为cls,类本身

    2. 实例函数,第一个参数为self

    def fun1():
        pass
    
    class cls1():
        def fun1(self):
            pass
        @classmethod
        def fun2(cls):
            pass
        @staticmethod
        def fun3():
            pass
    
    print fun1.__class__ #<type 'function'>
    print cls1.fun1.__class__ #<type 'instancemethod'>
    print cls1.fun2.__class__ #<type 'instancemethod'>
    print cls1.fun3.__class__ #<type 'function'>
  • 相关阅读:
    347. 前 K 个高频元素(桶排序、堆排序)
    322. 零钱兑换 && 416. 分割等和子集(0-1背包问题)
    739. 每日温度 && 503. 下一个更大元素 II (单调栈)
    1110. 删点成林
    个人纪录
    pub get failed (server unavailable) -- attempting retry 1 in 1 second?
    python 遍历文件夹重命名
    flutter vscode 连接iphone失败
    部署以太坊合约
    Web漏洞扫描工具AppScan10介绍
  • 原文地址:https://www.cnblogs.com/wongbingming/p/6847769.html
Copyright © 2011-2022 走看看