Understanding the dot notation in python

后端 未结 2 1384
情歌与酒
情歌与酒 2021-01-15 09:43

When I import a module, such as sys, I am assuming that I am importing a script, and in order to access its functions, I have to use the dot notation. For example, I want to

2条回答
  •  情话喂你
    2021-01-15 10:13

    Once you import a module (like sys or anything), the dot-notation may then refer to anything it contains. You could also import a 'package' contains modules, classes, methods in classes, functions in modules, etc.

    >>> import sys
    >>> type(sys)
    
    >>> sys.stderr
    <_io.TextIOWrapper name='' mode='w' encoding='cp437'>
    >>> type(sys.stderr)
    
    >>> type(sys.stderr.write)
    
    >>>
    

    It's meant to be generic sort-of-attribute access where each thing inside another is accessed via the dot, as if it was an attribute of that object, which it is.

    I believe it's meant to be ambiguous so that the user of a module/package does not need to be concerned with the implementation details of those objects. And if they change, as long as the structure and names are maintained, the actual object it refers to is not of concern to the user. They could always use type() or help() to look at the details or use other introspection tools.

提交回复
热议问题