Example analysis of a specialized method for a Python class

  • 2020-04-02 14:29:40
  • OfStack

This article illustrates a special method for a Python class. Share with you for your reference. Specific analysis is as follows:

Python classes can define specialized methods that are called by Python on your behalf in special cases or when special syntax is used, rather than directly in code (like normal methods).

1. The __init__

It's like a constructor

#!/usr/local/bin/python
class Study:
        def __init__(self,name=None):
                self.name = name
        def say(self):
                print self.name
study = Study("Badboy")
study.say()

2. __del__

It's like a destructor

#!/usr/local/bin/python
class Study:
        def __init__(self,name=None):
                self.name = name
        def __del__(self):
                print "Iamaway,baby!"
        def say(self):
                print self.name
study = Study("zhuzhengjun")
study.say()

3. __repr__

With repr(obj), the function is automatically called with s/s, which returns the string expression of the object,
Used to rebuild objects, if eval_r(repr(obj)) gets a copy of the object.

#!/usr/local/bin/python
class Study:
        def __init__(self,name=None):
                self.name = name
        def __del__(self):
                print "Iamaway,baby!"
        def say(self):
                print self.name
        def __repr__(self):
                return "Study('jacky')"
study = Study("zhuzhengjun")
study.say()
print type(repr(Study("zhuzhengjun"))) # str
print type(eval_r(repr(Study("zhuzhengjun")))) # instance
study = eval_r(repr(Study("zhuzhengjun")))
study.say()

4. The __str__

Python can print out a built-in data type with a print statement. Sometimes, a programmer wants to define a class whose object can also be printed with a print statement. A Python class can define a special method, s/s, that provides an informal string representation of an object of the class. If the client of the class contains the following statements:

print objectOfClass

Python then calls the method of the object with the string returned by that method.
#!/usr/local/bin/python
class PhoneNumber:
        def __init__(self,number):
                 self.areaCode=number[1:4]
                 self.exchange=number[6:9]
                 self.line=number[10:14]
        def __str__(self):
                return "(%s) %s-%s"%(self.areaCode,self.exchange,self.line)
def test():
         newNumber=raw_input("Enter phone number in the form. (123) 456-7890: n")
         phone=PhoneNumber(newNumber)
         print "The phone number is:"
         print phone
if__name__=="__main__":
         test()

Method s/s accepts a string in the form of "(XXX) xxx-xxxx". Each x in the string is a digit of the phone number. Method splits the string and stores different parts of the phone number as properties.
Method s/s is a special method that constructs and returns a string representation of an object of the PhoneNumber class. Once the parser encounters the following statement:

print phone

The following statement is executed:
print phone.__str__()

Python also calls the method s if the program passes the PhoneNumber object to the built-in function STR (such as STR (phone)) or USES the string formatting operator %(such as "%s"%phone) for the PhoneNumber object.
5. __cmp __

Comparison operator, 0: equals 1: greater than -1: less than

class Study: 
     def __cmp__(self, other):
         if other > 0 :
             return 1
         elif other < 0:
             return - 1
         else:
             return 0
study = Study()
if study > -10:print 'ok1'
if study < -10:print 'ok2'
if study == 0:print 'ok3'

Print: ok2 ok3

Note: python automatically calls the cmp__ method, such as -10, while the class is being compared < 0 returns -1, that is, the study should be smaller than -10, and the evaluation should print ok2

6. The __getitem__

S easy to use with this method. Like the normal methods clear, keys, and values, it simply redirects to the dictionary and returns the value of the dictionary.

class Zoo: 
     def __getitem__(self, key):
         if key == 'dog':return 'dog'
         elif key == 'pig':return  'pig'
         elif key == 'wolf':return 'wolf'
         else:return 'unknown'
zoo = Zoo()
print zoo['dog']
print zoo['pig']
print zoo['wolf']

Print:
Dog pig Wolf

7. __setitem__

S simply redirect to the real dictionary self.data and let it do the work.

class Zoo: 
     def __setitem__(self, key, value):
         print 'key=%s,value=%s' % (key, value)
zoo = Zoo()
zoo['a'] = 'a'
zoo['b'] = 'b'
zoo['c'] = 'c'

Print:
Key = a, value = a
Key = b, value = b
Key = c, value = c

8. __delitem__

Called while calling del instance[key], you may remember it as a way to remove a single element from the dictionary. When you use del in a class instance, Python calls the private method with arbitration for you.

class A: 
     def __delitem__(self, key):
         print 'delete item:%s' %key
a = A()
del a['key']

I hope this article has helped you with your Python programming.


Related articles: