python class and its methods

 

I. INTRODUCTION

In Python, an object-oriented programming has two main themes, that is, classes and class instances
class and instance:
class and instance of the interrelated: an object class is defined, and examples of "real physical", which is stored in the class object definitions
specific information.

This class has a number of advantages:

1, class object is polymorphic: that is a variety of forms, which means we can use the same method of operation for different classes of objects, without having to write additional code. 
2, encapsulation class: after packaging, the object class can be called directly to the internal operation of some methods of the class, so that the user does not need to see the details of the code works. 
3, class inheritance: class can inherit methods from other classes thereof metaclass or used directly.

Second, the definition of the class

1. Define class (class) Syntax

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

A first line, the syntax is the name behind the class followed by the class, and finally do not forget "colon", so to define a class.
The class name, initials, have a predetermined non-text, preferably capitalized, this requires the identification code in each class distinction.
The second line is the start method of the class, you see, and function is very similar, but with a common function is different it is that it has an internal "self", parameter, its role is to object references itself.

2. Initialize the object

When you create a class, you can define a specific method, named __init __ (), just create an instance of this class will be run this way. Parameter values ​​can be passed to the __init __ () method, so when you create an object property can be set to your desired __init __ () This method completes the initialization when creating objects

Copy the code
1 >>> class peo:
2 ...     def __init__(self,name,age,sex):
3 ...             self.Name = name
4 ...             self.Age = age
5 ...             self.Sex = sex
6 ...     def speak(self):
7 ...             print "my name" + self.Name
8 ... 
Copy the code

When the object instance of this class:

Copy the code
1 >>> zhangsan=peo("zhangsan",24,'man')
2 >>> print zhangsan.Age
3 24
4 >>> print zhangsan.Name
5 zhangsan
6 >>> print zhangsan.Sex
7 man
Copy the code

Used many times before self this parameter class is like a blueprint, the use of a class can create multiple object instances, speak () method is called, must know which object called it.

Here self parameter tells the object to which the method is invoked. This is called an instance reference.

 

3. class of private property:

  two at the beginning __private_attrs underscore stating that the property is private and can not be used in class or direct access to the outside. When used in a method of the class internal self .__ private_attrs
class methods
  within the class, the use of def keyword can be defined as a class method, and is generally different function definitions, methods must include the class parameter self, and as the first parameter
Private class method
  __private_method two begins with an underscore, the method is declared as a private method, external calls can not be in class. Call slef .__ private_methods within the class

 

4. classmethod class method

1) in python. @Classmethod class method is a function of modifier, it means that the following is a class method, but usually we see for instance the method is called. The first parameter cls class method, the first parameter is example of a method of self, showing such an example.
2) The method requires a general object of at least one self parameter representative of the class object instance
3) in the incoming methods cls class variables, can be used to do some processing related cls. And when there is a subclass inheritance, when calling such methods, the incoming class is a subclass of cls variable, rather than the parent class. For class methods can be invoked through the class, as Cf (), a little static methods in C ++ similar, it can also be called via an instance of a class, like C (). F (), where C (), write after such an instance it is the class.

Copy the code
Class info. 1 (Object): 
 2 
 . 3 @classmethod 
 . 4 DEF sayclassmethod (CLS): 
 . 5 
 . 6 Print 'say S%'% CLS 
 . 7 
 . 8 DEF saymethod (Self): 
 . 9 
10 Print 'say% S' Self% 
. 11 
12 is 
13 is Test info = () 
14 test.saymethod () method call ## example 
15 test.sayclassmethod () ## example calling a class method 
16 info.saymethod (test) ## class calls the instance method 
17 info.sayclassmethod () ## class calls class methods
Copy the code

We compare run.

 

The class @property decorator

Copy the code
Pager class. 1: 
 2 DEF the __init __ (Self, ALL_COUNT are): 
 . 3 = ALL_COUNT are self.all_count 
 . 4 @Property 
 . 5 DEF all_pager (Self): 
 . 6 A, B = divmod (self.all_count, 10) 
 . 7 IF A == 0: 
 . 8 A return 
 . 9 the else: 
10 + A return. 1 
. 11 
12 is all_pager.setter @ 
13 is DEF all_pager (Self, value): 
14 Print (value) 
15 
16 @ all_pager.deleter 
. 17 DEF all_pager (Self): 
18 is Print ( 'Hehe') 
Pager P =. 19 (101) 
20 is RET = methods method class attribute access objects # p.all_count 
21 is Print (RET)
Copy the code

Let's look at the second method

Copy the code
 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.foo
14 p.foo='alex'
15 print(p.foo)
16 del p.foo
Copy the code

Three functions defined in the class, are used as an assignment, value, delete variables

property function prototype for property (fget = None, fset = None, fdel = None, doc = None), the respective embodiments can be assigned according to their function defined.

 

 

Third, the derived class defines:
1. Single inheritance

class <class name> (parent name)
<statement>

1 class childbook(book)
2     age = 10

# Single inheritance example

Copy the code
 1  class student(people):  
 2         grade = ''  
 3         def __init__(self,n,a,w,g):  
 4             #调用父类的构函  
 5             people.__init__(self,n,a,w)  
 6             self.grade = g  
 7         #覆写父类的方法  
 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()
Copy the code

 

2. Class multiple inheritance
class name of the class (parent class 1, parent 2, ...., n-parent)
<statement 1>

Note that the order in parentheses parent class, if the parent class have the same method name, but did not specify when subclasses, when searching python from left to right, that method is not found in a subclass, from left to right Find the parent class contains methods

# Multiple inheritance before another class, ready  

Copy the code
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))  
Copy the code

# Multiple inheritance  

Copy the code
. 1 class Sample (Speaker, Student):   
2 A = ''   
. 3 DEF the __init __ (Self, n-, A, W, G, T):   
. 4 Student .__ the init __ (Self, n-, A, W, G)   
. 5 Speaker .__ init__ (Self, n-, T)   
. 6 
. 7 Test Sample = ( "Tim", 25,80,4, "the Python")   
. 8 test.speak () # same method name, is called by default before the parent row in parentheses Methods
Copy the code

 

 

Fourth, the kind of professional approach

Python class defines special methods, special methods are special cases or when specific syntax for you by Python call, rather than a direct call code (like normal methods).

1 __init__
similar constructor

Copy the code
1 #!/usr/local/bin/python
2 class Study:
3         def __init__(self,name=None):
4                 self.name = name
5         def say(self):
6                 print self.name
7 study = Study("Badboy")
8 study.say()
Copy the code

2 __del__
similar destructor

Copy the code
 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()
Copy the code

3__repr__
using repr (obj) when __repr__ will automatically call the function, the function returns the object string expression,
for reconstructing the object, if eval (repr (obj)) will get a copy of the object.

Copy the code
 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"))) # str
14 print type(eval(repr(Study("zhuzhengjun")))) # instance
15 
16 study = eval(repr(Study("zhuzhengjun")))
17 
18 study.say()
Copy the code

4__str__
Python print statement output can be built-in data types. Sometimes programmers want to define a class, asking it to object also can print statements output. Python class defines a special method __str__, not a string object class formal representation. If the class of the client contains the following statement:

print objectOfClass
then Python will call __str__ method of the object, and output the string returned by the method.

Copy the code
 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 phone
17 
18 if__name__=="__main__":
19          test()
Copy the code

__Init__ method of receiving a string of the form "(xxx) xxx-xxxx" of. Each string x is a digit phone number. The method of decomposing the string, and different parts of the phone number stored as properties.

__Str__ method is a special method, and it is configured to return a string representation of the object class PhoneNumber. Once the parser encounters the following statement:

print phone

We will execute the following statement:

print phone.__str__()

If the program object to the built-in function PhoneNumber str (such as str (phone)), or using string formatting operator% (e.g., "% s"% phone) as PhoneNumber object, Python also called __str__ method.

5__cmp __
comparison operators, 0: equal to 1: greater than -1: less than

Copy the code
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' 
Copy the code

Print: ok2 OK3
Description: When comparing the class, Python automatically calls __cmp__ method, such as -10 <0 -1, i.e. -10 and study should be small, estimated print ok2

6__getitem__
__getitem__ special method is very simple. Like ordinary methods clear, keys and values, as it just redirects to the dictionary, the dictionary of the return value.

Copy the code
 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']
Copy the code

Print dog pig wolf

7__setitem__
__setitem__ simply redirects to the real dictionary self.data, let it work.

Copy the code
 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 打印:
10 key=a,value=a
11 key=b,value=b
12 key=c,value=c
Copy the code

__Delitem__ is 8
__delitem__ is when you call del instance [key] call, you may remember as the way to delete individual items from a dictionary. When you use del on a class instance, __delitem__ Python special method call for you.

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

Guess you like

Origin www.cnblogs.com/aibabel/p/11030986.html