Variable scopes in Python classes

前端 未结 4 2121
谎友^
谎友^ 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:37

    we can use the scope in this for as : case 1: In the Class

    class test:
         def __init__(self, a):
              self.__elements = a
         def change_a(self): self.__elements = 5
    

    case 2 : Outside class

    t = test(5)
    

    This will access by as object._classname__privatevaribalename

    print(t._test__elements)
    

    this will print the change value of a

提交回复
热议问题