Accessing private variables in Python

Source: Internet
Author: User

Accessing private variables in Python

To give interns training in Python, I don't know how to use it, I can't fraught it, and look at some of the concepts in Python.

See the class and private variables, think of the previous read the article, said Python has a private function can also be called, and then search a bit, StackOverflow has a problem is to ask this. Why is Python ' s ' private ' methods not actually private?

How

Class with two underscores __, which is the private variable/function (which will say in fact not)

Write a Python code and run and see.

#!/usr/bin/env python#-*-Coding:utf-8-*-class A(Object):    def __init__( Self):        Super(A,  Self).__init__()         Self.name = "Childe"         Self.__age =  -    def Pub_f( Self):        Print ' This was a public function '    def __pri_f( Self):        Print ' This is a private function 'def Main():    a = A()    a.Pub_f()    Print a.name    Try:        a._pri_f()    except Attributeerror  as e:        Print e    Try:        Print a.__age    except Attributeerror  as e:        Print e    Print dir(a)if __name__ == ' __main__ ':    Main()

The results of the operation are as follows:

this is a public function  childe  ‘A‘ object has no attribute ‘__pri_f‘  ‘A‘ object has no attribute ‘__age‘  [‘_A__age‘, ‘_A__pri_f‘, ‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__module__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘name‘, ‘pub_f‘]  

You can see that the direct call to the private variable/function failed. But when Dir (a), there are 'aage', 'a_prif ' These two things to invoke.

#!/usr/bin/env python#-*-Coding:utf-8-*-class A(Object):    def __init__( Self):        Super(A,  Self).__init__()         Self.name = "Childe"         Self.__age =  -    def Pub_f( Self):        Print ' This was a public function '    def __pri_f( Self):        Print ' This is a private function 'def Main():    a = A()    Try:        a._a__pri_f()    except Attributeerror  as e:        Print e    Try:        Print a._a__age    except Attributeerror  as e:        Print eif __name__ == ' __main__ ':    Main()

Run, normal output.

This is a private function
28

Why

These are the PO Master's problem and his code, he asked not how, but why. I had an eye for the answer below (well, I was too ignorant). This time it really is the copy code:

class Foo(Object):    def __init__( Self):         Self.__baz =  the    def Foo( Self):        Print  Self.__bazclass Bar(Foo):    def __init__( Self):        Super(Bar,  Self).__init__()         Self.__baz =  +    def Bar( Self):        Print  Self.__bazx = Bar()x.Foo()x.Bar()Print x.__dict__

Operation Result:

42
21st
{'BarBaz ': +, 'Foo__baz ': 42}

In other words, the private variables of the subclass coexist with private variables of the same name in the parent class. I really don't know how to do that before.

At the same time, [Alya] answered the question,

The name scrambling is used to ensure that subclasses don ' t accidentally override the private methods and attributes of th Eir superclasses. It ' s not designed to prevent deliberate access from outside.

For those of you who are worse than me, I am lazy, that is to say, private variables are not intended to prevent external calls, but to avoid the quilt class being accidentally rewritten.

Since Alya only answered this question, go to the official website and look at the documentation for the class.

After watching, there is a feeling of being molested. The official website said that there is no private variable in Python, and an underscore starts with a "treat it as" a private variable, "suggest" do not change directly from the outside. At least two underscores that start with an underscore, such as Spam will be renamed to _classnameSpam

Well, when it comes to Python, you can talk a little bit more.

C++

The private variables in C + + should also be accessible/modified. Because the class instance is inside the stack space, the variables inside the class instance, whether private or public, are sequentially arranged in memory.

#include <iostream>using namespace STD;class  Person{     Public:         Person(){             This - Age =  -;        }    Private:        int  Age;};int Main(int argc, Const Char *argv[]){     Person P;    cout << *(int*)(&P) << Endl;    return 0;}
% ./a.out 28

I don't know how to call a private function, but I think there's a way.

Accessing private variables in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.