简体   繁体   中英

python leading and trailing underscores in user defined functions

How can i used the rt function, as i understand leading & trailing underscores __and__() is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,

class A(object):
  def __rt__(self,r):
      return "Yes special functions"


a=A()
print dir(a)
print a.rt('1') # AttributeError: 'A' object has no attribute 'rt'

But

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) #prints 1

Python doesn't translate one name into another. Specific operations will under the covers call a __special_method__ if it has been defined. For example, the __and__ method is called by Python to hook into the & operator, because the Python interpreter explicitly looks for that method and documented how it should be used.

In other words, calling object.rt() is not translated to object.__rt__() anywhere, not automatically.

Note that Python reserves such names; future versions of Python may use that name for a specific purpose and then your existing code using a __special_method__ name for your own purposes would break.

From the Reserved classes of identifiers section :

__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

You can ignore that advice of course. In that case, you'll have to write code that actually calls your method :

class SomeBaseClass:
    def rt(self):
        """Call the __rt__ special method"""
        try:
            return self.__rt__()
        except AttributeError:
            raise TypeError("The object doesn't support this operation")

and subclass from SomeBaseClass .

Again, Python won't automatically call your new methods. You still need to actually write such code.

Because there are builtin methods that you can overriden and then you can use them, ex __len__ -> len() , __str__ -> str() and etc.

Here is the list of these functions

The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of x.name) for class instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM