• 12 动态语言 __slots__


    1. 动态语言的定义

    动态编程语言 是 高级程序设计语言 的一个类别,在计算机科学领域已被广泛应用。它是一类 在运行时可以改变其结构的语言 :例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除或是其他结构上的变化。动态语言目前非常具有活力。例如JavaScript便是一个动态语言,除此之外如 PHP 、 Ruby 、 Python 等也都属于动态语言,而 C 、 C++ 等语言则不属于动态语言。----来自 维基百科

    .

    2. 运行的过程中给对象绑定(添加)属性

    >>> class Person(object):
        def __init__(self, name = None, age = None):
            self.name = name
            self.age = age
    
    
    >>> P = Person("小明", "24")
    >>>

    3. 运行的过程中给类绑定(添加)属性

    >>> P1 = Person("小丽", "25")
    >>> P1.sex
    
    Traceback (most recent call last):
      File "<pyshell#21>", line 1, in <module>
        P1.sex
    AttributeError: Person instance has no attribute 'sex'
    >>>

    我们尝试打印P1.sex,发现报错,P1没有sex这个属性!---- 给P这个实例绑定属性对P1这个实例不起作用! 那我们要给所有的Person的实例加上 sex属性怎么办呢? 答案就是直接给Person绑定属性!

    >>>> Person.sex = None #给类Person添加一个属性
    >>> P1 = Person("小丽", "25")
    >>> print(P1.sex) #如果P1这个实例对象中没有sex属性的话,那么就会访问它的类属性
    None #可以看到没有出现异常
    >>>

    4. 运行的过程中给类绑定(添加)方法    types.MethodType

    我们直接给Person绑定sex这个属性,重新实例化P1后,P1就有sex这个属性了! 那么function呢?怎么绑定?

    >>> class Person(object):
        def __init__(self, name = Non):
            self.name = name
    
        def eat(self):
            print("eat food")
    
    
    >>> def run(self, speed):
        print("%s在移动, 速度是 %d km/h"%(self.name, speed))
    
    
    >>> P = Person("老王")
    >>> P.eat()
    eat food
    >>> 
    >>> P.run()
    Traceback (most recent call last):
      File "<pyshell#5>", line 1, in <module>
        P.run()
    AttributeError: Person instance has no attribute 'run'
    
    
    >>> import types
    >>> P.run = types.MethodType(run, P)
    >>> P.run(180)
    老王在移动,速度是 180 km/h

        


    5.添加 静态方法,类方法

    #定义一个静态方法
    @staticmethod
    def testStatic():
        print("---static method----")
    
    #
    #给Person类绑定静态方法
    Person.testStatic = testStatic
    #调用静态方法
    Person.testStatic()
    #定义一个类方法
    @classmethod
    def testClass(cls):
        cls.num = 100
    
    #给Person类绑定类方法
    Person.testClass = testClass
    #调用类方法
    Person.testClass()

    6.__slots__ 

    现在我们终于明白了,动态语言与静态语言的不同

    动态语言:可以在运行的过程中,修改代码

    静态语言:编译时已经确定好代码,运行过程中不能修改

    In [1]: class Dog(object):
       ...:     def __init__(self,new_name):
       ...:         self.name = new_name
       ...:         
    
    In [2]: dog1 = Dog("jack")
    
    In [3]: print(dog1.name)
    jack
    
    
    
    ###可以给类里面添加其他属性
    
    In [7]: dog1.addr
    Out[7]: 'beijing'
    
    In [8]: dog1.age = 10
    
    In [9]: dog1.age
    Out[9]: 10

    为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:

    >>> class Person(object):
        __slots__ = ("name", "age")
    
    >>> P = Person()
    >>> P.name = "老王"
    >>> P.age = 20
    >>> P.score = 100
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
    AttributeError: Person instance has no attribute 'score'
    >>>

    注意:

    • 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
    In [67]: class Test(Person):
        ...:     pass
        ...:
    
    In [68]: t = Test()
    
    In [69]: t.score = 100
  • 相关阅读:
    爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离
    网络爬虫基础练习
    Mysql 使用 select into outfile
    Mysql 使用CMD 登陆
    使用Clean() 去掉由函数自动生成的字符串中的双引号
    Get Resultset from Oracle Stored procedure
    获取引用某个主键的所有外键的表
    Entity Framework 丢失数据链接的绑定,在已绑好的EDMX中提示“Choose Your Data Connection”
    添加MySql Metat Database 信息
    at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
  • 原文地址:https://www.cnblogs.com/venicid/p/7940687.html
Copyright © 2020-2023  润新知