Why does python not have a mechanism for data hiding?

cokofreedom at gmail.com cokofreedom at gmail.com
Fri Jun 6 09:03:00 CEST 2008


Someone asked about Java;

class FieldTest {
    public String publicString = "Foobar";
    private String privateString = "Hello, World!";
}

import java.lang.reflect.Field;

public class Test4 {
  public static void main(String args[]) {
    final Field fields[] =
        FieldTest.class.getDeclaredFields();
    for (int i = 0; i < fields.length; ++i) {
      System.out.println("Field: " + fields[i]);
    }
  }
}

OUTPUT >>>>
Field: public java.lang.String FieldTest.publicString
Field: private java.lang.String FieldTest.privateString

And to edit it;

import java.lang.reflect.Field;

public class Test7 {
  public static void main(String args[])
    throws Exception {
    final Field fields[] =
        FieldTest.class.getDeclaredFields();
    for (int i = 0; i < fields.length; ++i) {
      if ("privateString".equals(fields[i].getName())) {
        FieldTest fieldTest = new FieldTest();
        Field f = fields[i];
        f.setAccessible(true);
        System.out.println(f.get(fieldTest));
        f.set(fieldTest, "Modified Field");
        System.out.println(f.get(fieldTest));
        break;
      }
    }
  }
}

OUTPUT >>>>
Hello, World!
Modified Field

Enjoy.



More information about the Python-list mailing list