Variable scopes in Python classes

前端 未结 4 2091
谎友^
谎友^ 2020-11-22 00:15

Declaring a variable in a class (outside of a function): all class functions can access it (basically a public variable)

Declaring a variable inside a function insid

4条回答
  •  一生所求
    2020-11-22 00:23

    Declaring a variable at the top level of the class is like declaring a static or class variable. Qualifying it with self is declaring an instance variable. Class variables can be modified by referring to them by class name (e.g. Class.x = 5) and all instances will inherit these changes. Instance variables are private to an instance and can only be modified by that instance.

    You can achieve some level of access control using underscores. See private variables in the Python tutorial. By convention, variables starting with one underscore, e.g. _foo are non-public parts of an API, and names starting with two underscores e.g. __foo will have it's name mangled to be _classname__foo.

提交回复
热议问题