__slots__함수 사용

우리는python이 동적 언어라는 것을 안다. 실행하는 과정에서 코드를 수정할 수 있다.예를 들어 대상에게 속성을 증가시키고 클래스에 속성을 증가시키는 방법 등 조작을 한다.그러나 임의로 추가하거나 수정하는 데 제약이 없으면 프로그램의 건장성과 안전에 보장이 없다.
실제 개발에서 실례에 속성을 추가하여 제약을 한다면 파이톤은class를 정의할 때 특수한 를 정의할 수 있습니다slots__변수, 이class 실례가 추가할 수 있는 속성을 제한합니다.
class Person(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

    #    __slots__       “”  
    __slots__ = ("name", "age")

class Student(Person):
    def __init__(self,name,sex,age):
        super().__init__(name,age)
        self.sex = sex

p1 = Person("tom",18)
p1.sex = "male" #AttributeError: 'Person' object has no attribute 'sex',        

stu1 = Student("jack","male",22)
print(stu1.name,stu1.sex,stu1.age)
stu1.country= "china"
print(stu1.country)  #      __slots__    ,          。

python의 내장 (내장) 속성은 시스템이 자체로 가지고 있으며, 사용자가 패키지를 가져오지 않아도 바로 사용할 수 있는 속성입니다.어떻게python의 모든 내장 속성 (내장) 을 볼 수 있습니까?간단합니다. 내장 속성은 어디서나 사용할 수 있으니 전역 변수에 속할 것입니다. 글로벌스()를 사용하여 모든 전역 변수를 보면 가 있습니다.builtins__의 속성, 사용dict__바로 확인할 수 있습니다.
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': , 'a': 10, 'AA': , 'xx': {...}}
>>> AA = globals()
>>> AA['__builtins__'].__dict__
{'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.

Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': , '__spec__': ModuleSpec(name='builtins', loader=), '__build_class__': , '__import__': , 'abs': , 'all': , 'any': , 'ascii': , 'bin': , 'breakpoint': , 'callable': , 'chr': , 'compile': , 'delattr': , 'dir': , 'divmod': , 'eval': , 'exec': , 'format': , 'getattr': , 'globals': , 'hasattr': , 'hash': , 'hex': , 'id': , 'input': , 'isinstance': , 'issubclass': , 'iter': , 'len': , 'locals': , 'max': , 'min': , 'next': , 'oct': , 'ord': , 'pow': , 'print': , 'repr': , 'round': , 'setattr': , 'sorted': , 'sum': , 'vars': , 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': , 'memoryview': , 'bytearray': , 'bytes': , 'classmethod': , 'complex': , 'dict': , 'enumerate': , 'filter': , 'float': , 'frozenset': , 'property': , 'int': , 'list': , 'map': , 'object': , 'range': , 'reversed': , 'set': , 'slice': , 'staticmethod': , 'str': , 'super': , 'tuple': , 'type': , 'zip': , '__debug__': True, 'BaseException': , 'Exception': , 'TypeError': , 'StopAsyncIteration': , 'StopIteration': , 'GeneratorExit': , 'SystemExit': , 'KeyboardInterrupt': , 'ImportError': , 'ModuleNotFoundError': , 'OSError': , 'EnvironmentError': , 'IOError': , 'WindowsError': , 'EOFError': , 'RuntimeError': , 'RecursionError': , 'NotImplementedError': , 'NameError': , 'UnboundLocalError': , 'AttributeError': , 'SyntaxError': , 'IndentationError': , 'TabError': , 'LookupError': , 'IndexError': , 'KeyError': , 'ValueError': , 'UnicodeError': , 'UnicodeEncodeError': , 'UnicodeDecodeError': , 'UnicodeTranslateError': , 'AssertionError': , 'ArithmeticError': , 'FloatingPointError': , 'OverflowError': , 'ZeroDivisionError': , 'SystemError': , 'ReferenceError': , 'MemoryError': , 'BufferError': , 'Warning': , 'UserWarning': , 'DeprecationWarning': , 'PendingDeprecationWarning': , 'SyntaxWarning': , 'RuntimeWarning': , 'FutureWarning': , 'ImportWarning': , 'UnicodeWarning': , 'BytesWarning': , 'ResourceWarning': , 'ConnectionError': , 'BlockingIOError': , 'BrokenPipeError': , 'ChildProcessError': , 'ConnectionAbortedError': , 'ConnectionRefusedError': , 'ConnectionResetError': , 'FileExistsError': , 'FileNotFoundError': , 'IsADirectoryError': , 'NotADirectoryError': , 'InterruptedError': , 'PermissionError': , 'ProcessLookupError': , 'TimeoutError': , 'open': , 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit,

통일 성명: 오리지널 블로그의 내용에 대해 일부 내용은 인터넷에서 참고할 수 있고 만약에 오리지널 링크가 있으면 인용을 성명할 수 있다.만약 오리지널 링크를 찾을 수 없다면, 이 성명에서 권리 침해가 있으면 삭제에 연락하십시오.블로그 전재에 관하여 오리지널 링크가 있으면 성명한다.만약 오리지널 링크를 찾을 수 없다면, 이 성명에서 권리 침해가 있으면 삭제에 연락하십시오.

좋은 웹페이지 즐겨찾기