Variable scopes in Python classes

前端 未结 4 2201
谎友^
谎友^ 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条回答
  •  Happy的楠姐
    2020-11-22 00:18

    Although answered, let me add some comments to your questions:

    declaring a variable in a class (outside of a function) : all class functions can access it (basically a public variable): comment:this is like a static variable and can be called using the class name. These variables are available to all functions, any functions can modify it and print it.

    declaring a variable inside a function inside a class : only that function can access it (its in that functions scope): comment: if the variable is declared without self then it is accessible within that function only, kinda local variable. However if it declared using self like self.var= 'somevalue',, then it is accessible via any object but not via the class name.

    declaring a variable with self.(variable name) inside a function inside a class : all class functions can access it (how is this different from global (variable name)?): comment: see asnswer in the above part.

    and since there is no private / protected, everything is public, so everything accessible from inside a class is accessible from outside the class.: comment: yes, but we can use single underscore to tell world this variable is private but technically that actually doesnt make it private.

提交回复
热议问题