Python常用内装方法:_init__,__new__,__class__の使用について


pythonのすべてのクラスはobjectクラスをデフォルトで継承しているからです.objectクラスには元の組み込み属性やメソッドがたくさん用意されているので、ユーザーがカスタマイズしたクラスはPythonでもこれらの組み込み属性を継承します.dir()関数を使用して表示できます.pythonは多くの組み込み属性を提供していますが、実際に開発でよく使われているものは多くありません.多くのシステムが提供する組み込み属性は、実際の開発ではユーザーが書き換える必要があります.pythonでは、属性または関数を1つの属性として理解できます.
class Person(object):
    pass
#  python         (  )  
print(dir(Person)) #  dir()    
'''
['__lass__', '__delattr__', '__dict__', '__dir__', '__doc__','__eq__', '__format__', '__ge__', '__getattribute__',
 '__gt__','__hash__', '__init__', '__init_subclass__', '__le__', '__lt__','__cmodule__', '__ne__',
 '__new__', '__reduce__', '__reduce_ex__','__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__','__weakref__']

'''

1.一般的な組み込み属性:_init__および_new__
1.__init__       :
  1.         ,              ,          
  2.              
  3.           ,      object ,      ,    ,    ,  ,     
class Student(object):
    def __init__(self,name):
        self.name = name
        print("  __init__  ")

s = Student("tom")  
'''
  __init__  
'''

2.__new__       
  1.__new__  :          ,        。
  2.         ,         cls,  cls,        ,         Python       
  3.                ,        ,                ,           。
  4.           ,       。return  __new__     ,     object __new__        


class Student(object):
    def __init__(self,name):
        self.name = name
        print("  __init__  ")

    def __new__(cls, *args, **kwargs):
        print("  __new__  ")
        return object.__new__(cls)

s = Student("tom")
'''    :  __new__      __init__  
  __new__  
  _init__  
'''

3.__init__ __new__     
  1.__init__      self,         , python       ,         __new__     
  2.   __init__ __new__                  

class Student(object):
    def __init__(self,name):
        self.name = name
        print("  __init__  ")

    def __new__(cls, *args, **kwargs):
        print("  __new__  ")
        id =object.__new__(cls)
        print(id) #    __new__               
        return id
s1 = Student("JACK")
print(s1)
'''
  __new__  
<__main__.student object="" at="">
  __init__  
<__main__.student object="" at="">
'''

  :   ,            ,  __init__       __new__   。
   

についてnew__の実際の開発使用については、python使用_を参照してください.new__単一モードでオブジェクトを作成
2.一般的な組み込み属性:_class__
1.__class__     :
    1.__class__   type()    ,          。
    2.__class__    

class Student(object):
    def __init__(self,name):
        self.name = name
stu = Student("tom")
print(type(stu),type(Student))
print(stu.__class__, Student.__class__, stu.__class__.__class__)
'''    :
 
  
'''

pythonの組み込み(組み込み)属性はシステムが持参したもので,ユーザがパッケージをインポートすることなく直接使用できる属性である.pythonのすべての組み込みプロパティ(組み込み)を表示するにはどうすればいいですか?簡単です.組み込み属性はどこでも使用できる以上、グローバル変数に属します.globals()を使用してすべてのグローバル変数を表示すると、1つの__が表示されます.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,

統一声明:オリジナルブログの内容については、一部の内容がインターネットから参照されている可能性があります.オリジナルリンクがあれば参照を宣言します.オリジナルリンクが見つからない場合は、権利侵害がある場合は削除に連絡してください.ブログの転載については、オリジナルリンクがあれば声明します.オリジナルリンクが見つからない場合は、権利侵害がある場合は削除に連絡してください.