zoukankan      html  css  js  c++  java
  • python 使用__slots__

    使用__slots__:
    
    正常情况下,当我们定义了一个class,创建了夜歌class的实例后,我们可以给该梳理绑定任何属性和方法,
    
    给实例绑定一个属性:
    
    
    class Student(object):
       pass
    s=Student()
    s.name='aaa'
    print s.name
    
    
    
    给class 绑定方法:
    
    
    
    使用__slots__
    
    class Student(object):
       pass
    s=Student()
    s.name='aaaa'
    s.score='bbbb'
    s.age='ccc'
    print s.name
    print s.score
    print s.age
    
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py
    aaaa
    bbbb
    ccc
    
    
    为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性:
    
    
    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    class Student(object):
        __slots__ = ('name', 'age')  # 用tuple定义允许绑定的属性名称
    s=Student()
    s.name='aaaa'
    s.score='bbbb'
    s.age='ccc'
    print s.name
    print s.score
    print s.age
    
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py
    Traceback (most recent call last):
      File "C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py", line 7, in <module>
        s.score='bbbb'
    AttributeError: 'Student' object has no attribute 'score'

  • 相关阅读:
    with
    网编
    选课新系统大作业
    网络编程

    知识点
    Python
    学生选课大作业
    理解position与anchorPoint[转]
    毛玻璃效果的简单使用
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349443.html
Copyright © 2011-2022 走看看