Skip to main content





How to understand difference between _, __ and __xx__ in Python....??


1) One underline in the beginning
Python doesn't have real private methods, so one underline in the beginning of a method or attribute means you shouldn't access this method, because it's not part of the API. It's very common when using properties:
class BaseForm(StrAndUnicode):
    ...
    
    def _get_errors(self):
        "Returns an ErrorDict for the data provided for the form"
        if self._errors is None:
            self.full_clean()
        return self._errors
    
    errors = property(_get_errors)
This snippet was taken from django source code (django/forms/forms.py). This meanserrors is a property, and it's part of the API, but the method this property calls,_get_errors, is "private", so you shouldn't access it.

2) Two underlines in the beginning

This one causes a lot of confusion. It should not be used to mark a method as private, the goal here is to avoid your method to be overridden by a subclass. Let's see an example:
class A(object):
    def __method(self):
        print "I'm a method in A"
    
    def method(self):
        self.__method()
     
a = A()
a.method()
The output here is
$ python example.py 
I'm a method in A
Fine, as we expected. Now let's subclass A and customize __method
class B(A):
    def __method(self):
        print "I'm a method in B"

b = B()
b.method()
and now the output is...
$ python example.py
I'm a method in A
as you can see, A.method() didn't call B.__method() as we could expect. Actually this is the correct behavior for __. So when you create a method starting with __ you're saying that you don't want anybody to override it, it will be accessible just from inside the own class.
How python does it? Simple, it just renames the method. Take a look:
a = A()
a._A__method()  # never use this!! please!
$ python example.py
I'm a method in A
If you try to access a.__method() it won't work either, as I said, __method is just accessible inside the class itself.

3) Two underlines in the beginning and in the end

When you see a method like __this__, the rule is simple: don't call it. Why? Because it means it's a method python calls, not you. Take a look:
>>> name = "rdx"
>>> name.__len__()
3
>>> len(name)
3

>>> number = 20
>>> number.__add__(20)

There is always an operator or native function that calls these magic methods. The idea here is to give you the ability to override operators in your own classes. Sometimes it's just a hook python calls in specific situations. __init__(), for example, is called when the object is created so you can initialize it. __new__() is called to build the instance, and so on...
Here's an example:
class CrazyNumber(object):
    
    def __init__(self, n):
        self.n = n
    
    def __add__(self, other):
        return self.n - other
    
    def __sub__(self, other):
        return self.n + other
    
    def __str__(self):
        return str(self.n)


num = CrazyNumber(10)
print num           # 10
print num + 5       # 5
print num - 20      # 30
Another example:
class Room(object):

    def __init__(self):
        self.people = []

    def add(self, person):
        self.people.append(person)

    def __len__(self):
        return len(self.people)

room = Room()
room.add("Igor")
print len(room)     # 1
The documentation covers all these special methods.

Conclusion

Use _one_underline to mark you methods as not part of the API. Use__two_underlines__ when you're creating objects to look like native python objects or you wan't to customize behavior in specific situations. And don't use__just_to_underlines, unless you really know what you're doing!

Popular posts from this blog

How to read or extract text data from passport using python utility.

Hi ,  Lets get start with some utility which can be really helpful in extracting the text data from passport documents which can be images, pdf.  So instead of jumping to code directly lets understand the MRZ, & how it works basically. MRZ Parser :                 A machine-readable passport (MRP) is a machine-readable travel document (MRTD) with the data on the identity page encoded in optical character recognition format Most travel passports worldwide are MRPs.  It can have 2 lines or 3 lines of machine-readable data. This method allows to process MRZ written in accordance with ICAO Document 9303 (endorsed by the International Organization for Standardization and the International Electrotechnical Commission as ISO/IEC 7501-1)). Some applications will need to be able to scan such data of someway, so one of the easiest methods is to recognize it from an image file. I 'll show you how to retrieve the MRZ information from a picture of a passport using the PassportE

How to generate class diagrams pictures in a Django/Open-edX project from console

A class diagram in the Unified Modeling Language ( UML ) is a type of static structure diagram that describes the structure of a system by showing the system’s classes, their attributes, operations (or methods), and the relationships among objects. https://github.com/django-extensions/django-extensions Step 1:   Install django extensions Command:  pip install django-extensions Step 2:  Add to installed apps INSTALLED_APPS = ( ... 'django_extensions' , ... ) Step 3:  Install diagrams generators You have to choose between two diagram generators: Graphviz or Dotplus before using the command or you will get: python manage.py graph_models -a -o myapp_models.png Note:  I prefer to use   pydotplus   as it easier to install than Graphviz and its dependencies so we use   pip install pydotplus . Command:  pip install pydotplus Step 4:  Generate diagrams Now we have everything installed and ready to generate diagrams using the comm

How to Remove course from Open-edX

Go to vagrant  => 1. In the edx-platform directory:  - cd /edx/app/edxapp/edx-platform 2. Run the following Django management command:   - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp lms dump_course_ids --settings aws    - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp lms dump_course_ids --settings=devstack 3. Find the course ID which you'd like to delete in the resulting list of course IDs. 4. Copy the course ID into the following command and run it:  - sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp cms delete_course <COURSE_ID> --settings aws  -   sudo -u www-data /edx/bin/python.edxapp /edx/bin/manage.edxapp cms delete_course <COURSE_ID> --settings=devstack  - You'll be asked to verify the deletion . To verify the deletion, run the command from step 2 above and ensure that the course ID is not in the list. Help reference : https://openedx.atlassian.net/wiki/spa