为了账号安全,请及时绑定邮箱和手机立即绑定
慕课网数字资源数据库体验端
python进阶_学习笔记_慕课网
为了账号安全,请及时绑定邮箱和手机立即绑定

python进阶

廖雪峰 移动开发工程师
难度中级
时长 3小时33分
  • super(Student,self).__init__(name,gender)#初始化父类


    查看全部
  • 思考题

    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 isinstance(s,Student):
               return cmp(self.name,s.name)
           else:
               return cmp(self.name,s)
    L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
    print sorted(L)

    查看全部
    0 采集 收起 来源:python中 __cmp__

    2018-05-16

  • import simplejson as json这样写的好处是当上面的json无法使用时可以使用下面的json,如果不加as,上面的出错,则下面的代码需要改为simplejson.dumps

    查看全部
  • 导入包后,运行代码都是False,但是通过代码需要第一个是true,,,,那就手动凑一个,哈哈哈

    查看全部
  • cmp判断都被变成小写字母的字符串,通过lambda返回给cmp,再由sorted进行排序

    查看全部
    0 采集 收起 来源:python中偏函数

    2018-05-16

  • 如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。

    顾名思义,__slots__是指一个类允许的属性列表:

    class Student(object):
        __slots__ = ('name', 'gender', 'score')
        def __init__(self, name, gender, score):
            self.name = name
            self.gender = gender
            self.score = score


    查看全部
    0 采集 收起 来源:python中 __slots__

    2018-05-16

  • 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

    注意: 第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品。

    现在,就可以像使用属性一样设置score了:

    >>> s = Student('Bob', 59)
    >>> s.score = 60
    >>> print s.score
    60
    >>> s.score = 1000
    Traceback (most recent call last):
      ...
    ValueError: invalid score


    查看全部
    0 采集 收起 来源:python中 @property

    2018-05-16

  • 因为 Python 定义了__str__()和__repr__()两种方法,__str__()用于显示给用户,而__repr__()用于显示给开发人员。

    查看全部
  • ,如果已知一个属性名称,要获取或者设置对象的属性,就需要用 getattr() 和 setattr( )函数了:

    查看全部
  • 其次,可以用 dir() 函数获取变量的所有属性:

    >>> dir(123)   # 整数也有很多属性...['__abs__', '__add__', '__and__', '__class__', '__cmp__', ...]
    
    >>> dir(s)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'gender', 'name', 'score', 'whoAmI']


    查看全部
  • 首先可以用 type() 函数获取变量的类型,它返回一个 Type 对象:

    >>> type(123)
    <type 'int'>
    >>> s = Student('Bob', 'Male', 88)
    >>> type(s)
    <class '__main__.Student'>


    查看全部
  • >>> isinstance(s, Person)
    True    # s是Person类型>>> isinstance(s, Student)
    True    # s是Student类型>>> isinstance(s, Teacher)
    False   # s不是Teacher类型


    查看全部
  • 当我们拿到变量 p、s、t 时,可以使用 isinstance 判断类型:

    >>> isinstance(p, Person)
    True    # p是Person类型>>> isinstance(p, Student)
    False   # p不是Student类型>>> isinstance(p, Teacher)
    False   # p不是Teacher类型


    查看全部
  • class Student(Person):
        def __init__(self, name, gender, score):        super(Student, self).__init__(name, gender)
            self.score = score

    一定要用 super(Student, self).__init__(name, gender) 去初始化父类,否则,继承自 Person 的 Student 将没有 name 和 gender。

    函数super(Student, self)将返回当前类继承的父类,即 Person ,然后调用__init__()方法,注意self参数已在super()中传入,在__init__()中将隐式传递,不需要写出(也不能写)。


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

     

    • ?不会了怎么办

    • 要定义关键字参数,使用 **kw;

      除了可以直接使用self.name = 'xxx'设置一个属性外,还可以通过 setattr(self, 'name', 'xxx') 设置属性。

      参考代码:

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


    查看全部

举报

0/150
提交
取消
课程须知
本课程是Python入门的后续课程 1、掌握Python编程的基础知识 2、掌握Python函数的编写 3、对面向对象编程有所了解更佳
老师告诉你能学到什么?
1、什么是函数式编程 2、Python的函数式编程特点 3、Python的模块 4、Python面向对象编程 5、Python强大的定制类
友情提示:

您好,此课程属于迁移课程,您已购买该课程,无需重复购买,感谢您对慕课网的支持!