Python class and its method, python Class Method

Source: Internet
Author: User

Python class and its method, python Class Method

                Python class and its method

I. Introduction

In Python, object-oriented programming has two main themes: classes and class instances.
Class and instance:
Classes and instances are associated with each other: classes are the definition of objects, while instances are "real objects". they store the objects defined in the classes.
.

Class has the following advantages:

1. class objects are polymorphism: multiple forms, which means that we can use the same operation method for different class objects without additional code writing. 2. encapsulation of classes: after encapsulation, you can directly call class objects to operate some internal class methods without allowing users to see the details of code work. 3. Inheritance of classes: classes can be directly used to inherit their methods from other classes or meta classes.

Ii. Class Definition

1. Define the class syntax

1 >>> class Iplaypython:2 >>>     def fname(self, name):3 >>>           self.name = name

First line, the syntax is followed by the class name. Do not forget the "colon" to define a class.
Class Name, first letter, there is a non-printable rule, preferably in upper case, you need to identify and distinguish each class in the code.
The second line starts with a class method. As you can see, it is very similar to a function, but unlike a common function, it has a "self" parameter, it is used to reference the object itself.

2. initialize the object

When creating a class, you can define a specific method named _ init _ (). This method is run as long as an instance of this class is created. You can pass parameters to the _ init _ () method, so that when creating an object, you can set the attribute as the expected value _ init __() this method will complete initialization when the object is created

1 >>> class peo:2 ...     def __init__(self,name,age,sex):3 ...             self.Name = name4 ...             self.Age = age5 ...             self.Sex = sex6 ...     def speak(self):7 ...             print "my name" + self.Name8 ... 

When instantiating the object of this class:

1 >>> zhangsan=peo("zhangsan",24,'man')2 >>> print zhangsan.Age3 244 >>> print zhangsan.Name5 zhangsan6 >>> print zhangsan.Sex7 man

Previously, the self parameter class was used multiple times as a blueprint. A class can be used to create multiple object instances. When the speak () method is called, you must know which object has called it.

Here, the self parameter will tell which object the method is called. This is called instance reference.

 

3. Private attributes of the class:

_ Private_attrs starts with an underscore and declares that this attribute is private and cannot be used outside the class or accessed directly. Self. _ private_attrs used in internal methods of the class
Class Method
Inside the class, you can use the def keyword to define a method for the class. Unlike the general function definition, the class method must contain the self parameter and be the first parameter.
Private Class Method
_ Private_method starts with two underscores. It is declared as a private method and cannot be called outside the class. Call slef. _ private_methods inside the class

 

4. classmethod Class Method

1) in python, The. Class Method @ classmethod is a function modifier, which indicates the next class method. What we usually see is the instance method. The first parameter cls of the class method, and the first parameter of the instance method is self, which indicates an instance of the class.
2) A common object method requires at least one self parameter, representing a class object instance.
3) the class method is passed in with the class variable cls, so that you can use cls for related processing. In addition, when a subclass is inherited and this class method is called, The passed-in class variable cls is a subclass rather than a parent class. Class methods can be called through classes, just like C. f () is similar to the static method in C ++. It can also be called through an instance of the class, just like C (). f (), Here C () is written as this, and then it is an instance of the class.

1 class info (object): 2 3 @ classmethod 4 def sayclassmethod (cls): 5 6 print 'say % s' % cls 7 8 def saymethod (self ): 9 10 print 'say % s' % self11 12 13 test = info () 14 test. saymethod () # instance call Method 15 test. sayclassmethod () # instance call class Method 16 info. saymethod (test) # class call instance method 17 info. sayclassmethod () # class call class Method

Let's compare and run it.

 

5. Class decorators @ property

1 class Pager: 2 def _ init _ (self, all_count): 3 self. all_count = all_count 4 @ property 5 def all_pager (self): 6 a, B = divmod (self. all_count, 10) 7 if a = 0: 8 return a 9 else: 10 return a + 111 12 @ all_pager.setter13 def all_pager (self, value): 14 print (value) 15 16 @ all_pager.deleter17 def all_pager (self): 18 print ('hehe ') 19 p = Pager (101) 20 ret = p. all_count # Method 21 print (ret)

The second method is as follows:

 1 class Pager: 2     def __init__(self,all_count): 3         self.all_count=all_count 4     def f1(self): 5         return 123 6     def f2(self,value): 7         print('======') 8     def f3(self): 9         print('+++++++')10 11     foo=property(fget=f1,fset=f2,fdel=f3)12 p=Pager(101)13 ret=p.foo14 p.foo='alex'15 print(p.foo)16 del p.foo

Define three functions in this class for assignment, value, and deletion of variables.

The prototype of the property function is property (fget = None, fset = None, fdel = None, doc = None). In the preceding example, assign values to the corresponding function.

 

 

Iii. Inheritance class definition:
1. Single inheritance

Class <class Name> (parent class name)
<Statement>

1 class childbook(book)2     age = 10

# Single inheritance example

1 class student (people): 2 grade = ''3 def _ init _ (self, n, a, w, g ): 4 # Call the structure Letter of the parent class 5 people. _ init _ (self, n, a, w) 6 self. grade = g 7 # override the parent class method 8 def speak (self): 9 print ("% s is speaking: I am % d years old, and I am in grade % d "% (self. name, self. age, self. grade) 10 11 s = student ('ken', 20, 60, 3) 12 s. speak ()

 

2. Multi-inheritance of Classes
Class name (parent class 1, parent class 2,..., parent class n)
<Statement 1>

Note the sequence of the parent class in parentheses. If the parent class has the same method name but is not specified in the subclass, search for python from left to right, that is, if the method is not found in the subclass, you can check from left to right whether the parent class contains the method.

# Another class, preparations before multi-Inheritance

1 class speaker():  2     topic = ''  3     name = ''  4     def __init__(self,n,t):  5         self.name = n  6         self.topic = t  7     def speak(self):  8         print("I am %s,I am a speaker!My topic is %s"%(self.name,self.topic))  

# Multi-Inheritance

1 class sample (speaker, student): 2 a = ''3 def _ init _ (self, n, a, w, g, t): 4 student. _ init _ (self, n, a, w, g) 5 speaker. _ init _ (self, n, t) 6 7 test = sample ("Tim", 25, 80, 4, "Python") 8 test. speak () # The method name is the same. By default, the method of the parent class is called in brackets.

 

 

Iv. Professional category Methods

A Python class can define a special method. A special method is called by Python for you in special circumstances or when special syntax is used, instead of calling it directly in the Code (like a common method ).

1 _ init __
Similar to Constructor

1 #!/usr/local/bin/python2 class Study:3         def __init__(self,name=None):4                 self.name = name5         def say(self):6                 print self.name7 study = Study("Badboy")8 study.say()

2 _ del __
Similar to destructor

 1 #!/usr/local/bin/python 2 class Study: 3         def __init__(self,name=None): 4                 self.name = name 5         def __del__(self): 6                 print "Iamaway,baby!" 7         def say(self): 8                 print self.name 9 study = Study("zhuzhengjun")10 study.say()

3 _ repr __
When repr (obj) is used, the _ repr _ function is automatically called, which returns the object string expression,
Used to reconstruct an object. If eval (repr (obj) is used, an object is copied.

 1 #!/usr/local/bin/python 2 class Study: 3         def __init__(self,name=None): 4                 self.name = name 5         def __del__(self): 6                 print "Iamaway,baby!" 7         def say(self): 8                 print self.name 9         def __repr__(self):10                 return "Study('jacky')"11 study = Study("zhuzhengjun")12 study.say()13 print type(repr(Study("zhuzhengjun"))) # str14 print type(eval(repr(Study("zhuzhengjun")))) # instance15 16 study = eval(repr(Study("zhuzhengjun")))17 18 study.say()

4 _ str __
Python can use the print statement to output built-in data types. Sometimes, programmers want to define a class and require its objects to be Output Using print statements. A Python class can define special method _ str __, which provides an informal string representation for class objects. If the client program of the class contains the following statements:

Print objectOfClass
Python will call the _ str _ method of the object and output the string returned by that method.

 1 #!/usr/local/bin/python 2  3 class PhoneNumber: 4         def __init__(self,number): 5                  self.areaCode=number[1:4] 6                  self.exchange=number[6:9] 7                  self.line=number[10:14] 8  9         def __str__(self):10                 return "(%s) %s-%s"%(self.areaCode,self.exchange,self.line)11 12 def test():13          newNumber=raw_input("Enter phone number in the form. (123) 456-7890: \n")14          phone=PhoneNumber(newNumber)15          print "The phone number is:"16          print phone17 18 if__name__=="__main__":19          test()

Method _ init _ receives a string, such as "(xxx) xxx-xxxx. Each x in the string is the single digit of the phone number. Method to break down the string and store different parts of the phone number as attributes.

Method _ str _ is a special method that constructs and returns a string representation of an object in the PhoneNumber class. The parser encounters the following statement:

print phone

The following statement is executed:

print phone.__str__()

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 ), python also calls the _ str _ method.

5 _ cmp __
Comparison operator, 0: equal to 1: greater than-1: less

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: When comparing classes, python automatically calls the _ cmp _ method, for example,-10 <0 returns-1, that is, study should be smaller than-10, and ok2 is estimated to be printed.

6 _ getitem __
The _ getitem _ special method is simple. Like normal methods clear, keys, and values, it only redirects to the dictionary and returns the dictionary value.

 1 class Zoo:   2      def __getitem__(self, key):   3          if key == 'dog':return 'dog'   4          elif key == 'pig':return  'pig'   5          elif key == 'wolf':return 'wolf'   6          else:return 'unknown'   7     8 zoo = Zoo()   9 print zoo['dog']  10 print zoo['pig']  11 print zoo['wolf']

Print dog pig wolf

7 _ setitem __
_ Setitem _ simply redirects to the real dictionary self. data to allow it to work.

1 class Zoo: 2 def _ setitem _ (self, key, value): 3 print 'key = % s, value = % s' % (key, value) 4 5 zoo = Zoo () 6 zoo ['a'] = 'A' 7 zoo ['B'] = 'B' 8 zoo ['C'] = 'C' 9 print: 10 key = a, value = a11 key = B, value = b12 key = c, value = c

8 _ delitem __
_ Delitem _ is called when del instance [key] is called. You may remember it as a method to delete a single element from the dictionary. When you use del in a class instance, Python calls the _ delitem _ special method for you.

1 class A:  2      def __delitem__(self, key):  3          print 'delete item:%s' %key  4    5 a = A()  6 del a['key'] 

 

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.