zoukankan      html  css  js  c++  java
  • Python学习笔记(十)

    一、类和构造函数的定义

      class 类名(object):
        def __init__(self,name,score):
          self.name = name
          self.score = score
        def show_info(self):
          print("name=",name,"score=",score)

      类名通常大写


    二、通过变量生成实例

      student1 = Student("cq",100)


    三、自由的为对象实例添加属性

      student1 = Student("cq",100)
      student1.school = "school"


    四、访问权限限制

      name : public的,外界可访问
      __name__ :特殊的,外界可以访问
      __name:私有的
      _name:私有的,外界可访问,但请将其视为私有的


    五、获取对象信息

      type(对象)
      type(123)==int

      import types
      type(fn) = types.FunctionType #判断是否为函数类型
      type(fn) == types.BuiltinFunctionType
      type(fn) == types.LambdaType
      type(fn) == types.GeneratorType

      isinstance(对象,类型)

      dir(对象)


    六、__XX__特殊方法

      类似__XX__的是特殊方法,在Python中有特殊用途,例如使用len()函数时将自动调用对象中的__len__


    七、动态增加实例属性

      对象.属性 = 属性值


    八、类属性

      类属性是属于类的,可以在类中直接定义,但其实例也可以访问类属性

      class Person:
        name = "CQ"
        def __init__(self):
          pass


    九、动态绑定方法

      def show_info(self):
        print("Hello World!")

      from types import MethodTypes
      s.show_info = MethodTypes(show_info(),s)
      s.show_info()


    十、动态绑定类方法

      from types import MethodTypes

      calss S(object):
        pass

      def show(self):
        print("Hello")

      s1 = S()
      s1.show()


    十一、限制动态添加的实例属性

      Python语言支持限制可以动态添加的实例属性,通过__slots__可指定动态添加的属性

      class S(object):
        __solts__ = ("name","age")


    十二、为类设置属性

      通过使用Python内置的装饰器@property可以将方法中的变量设置为属性,@property设置于getter方法

      class Student(object):
        def __init__(self,name,age):
          self.__name = name
          self.__age = age
        @property
        def name(self):
          return self.__name
        @name.setter
        def name(self,value):
          self.__name = value
        @proprety
        def age(self):
          return self.__age

        本实例中将 get_name 和 set_name 合并封装为了类的属性name,并将age封装设置为了类的只读属性
        

      

  • 相关阅读:
    web页面性能优化之接口前置
    python大佬养成计划----flask_bootstrap装饰网页
    撸个查询物流的小程序,欢迎体验
    FullCalendar插件的基本使用
    GeekforGeeks Trie
    使用Django和Python创建Json response
    nginx-gridfs的安装
    Linux kernel config and makefile system
    hadoop日志分析
    安装STS报错(三)
  • 原文地址:https://www.cnblogs.com/userchencq/p/7529976.html
Copyright © 2011-2022 走看看