Object-oriented advanced, python object-oriented advanced

Source: Internet
Author: User

Object-oriented advanced, python object-oriented advanced

This topic describes the Python class members, member modifiers, and special members of the class.

The class member diagram is as follows:

Note: Only the content of common fields in all members is stored in the object, that is, according to the number of objects created in this class, there are many common fields in the memory. Other members are stored in the class, that is, only one copy is created in the memory regardless of the number of objects.

I. Fields

Fields are classified into static fields and common fields. static fields belong to common fields of the class and belong to objects. The most essential difference is that they have different locations in the memory. static fields only have one copy in the class, for a common field, each object has a specific difference, see the code.

Class Province: # static field country = 'China' def _ init _ (self, name): # common field self. name = name # directly access the common field obj = Province ('hebei Province ') print obj. name # directly access the static field Province. country

When creating an object through a class, if each object has the same field, it can be replaced by a static field.

Ii. Method

Methods include common methods, static methods, and class methods.The memory belongs to the class.The difference is that the call method is different.

  • Common method:ObjectCall; at least oneSelfParameter.ObjectAssignedSelf;
  • Class Method:ClassCall; at least oneClsParameter.ClassCopyCls;
  • Static Method:ClassCall; no default parameter;

See the code

Class Foo: def _ init _ (self, name): self. name = name def ord_func (self): "" defines common methods. There must be at least one self parameter "" # print self. name print 'normal method' @ classmethod def class_func (cls): "defines class methods. There must be at least one cls parameter" print 'class method' @ staticmethod def static_func (): "defines static methods, no default parameter" print 'static method' # call common method f = Foo () f. ord_func () # Call the class method Foo. class_func () # Call the static method Foo. static_func ()

Similarities: all methods belong to the class (non-object). Therefore, only one copy is saved in the memory.

Differences: different method callers and different parameters automatically passed in when a method is called.

Iii. Attributes

Attribute is a variant of the method. below is the basic definition and usage of the attribute.

################ Definition ############### class Foo: def func (self): pass # define the property @ property def prop (self ): pass ################ call ############### foo_obj = Foo () foo_obj.func () foo_obj.prop # Call attributes

The attribute can be defined in two ways.

  • Decorator: Apply the decorator to the method.
  • Static field: the static field of the property object defined in the class.

We know that classes in Python have classic classes and new style classes, and the attributes of new classes are richer than those of classic classes. (If the class inherits the object, the class is a new class)
ClassicWith a @ property modifier

################ Definition ############### class Goods: @ property def price (self ): return "wupeiqi" ################ call ############### obj = Goods () result = obj. price # automatically execute the @ property modified price method and obtain the return value of the Method

The new category has three ways to access the decoration Device

################ Definition ############### class Goods (object ): @ property def price (self): print '@ properties' @ price. setter def price (self, value): print '@ price. setter '@ price. deleter def price (self): print '@ price. deleter '################ call ############### obj = Goods () obj. price # automatically execute the price method modified by @ property and obtain the return value obj of the method. price = 123 # Automatic Execution @ price. the price method modified by setter, and assign 123 to the method parameter del obj. price # Automatic Execution @ price. the price method modified by deleter

There is also an application instance below

Class Goods (object): def _ init _ (self): # original price self. original_price = 100 # discount self. discount = 0.8 @ property def price (self): # actual price = original price * discount new_price = self. original_price * self. discount return new_price @ price. setter def price (self, value): self. original_price = value @ price. deltter def price (self, value): del self. original_priceobj = Goods () obj. price # Get product price obj. price = 200 # modify the original price of the product del obj. price # Delete the original price of a product

Create a static field of the priperty object. This field is irrelevant to the class.

Class Foo: def get_bar (self): return 'wupeiqi 'BAR = property (get_bar) obj = Foo () reuslt = obj. BAR # automatically call the get_bar method and obtain the returned value of the method print reuslt

The property constructor has four parameters.

  • The first parameter isMethod Name, CallObject. AttributeAutomatically trigger execution Method
  • The second parameter isMethod Name, CallObject. Property = XXXAutomatically trigger execution Method
  • The third parameter isMethod Name, CallDel object. AttributeAutomatically trigger execution Method
  • The fourth parameter isString, CallObject. Property. _ doc __This parameter is the description of this attribute.
  • Class Foo: def get_bar (self): return 'wupeiqi '# * two parameters required: def set_bar (self, value): return 'set value' + value def del_bar (self ): return 'wupeiqi 'BAR = property (get_bar, set_bar, del_bar, 'description... ') obj = Foo () obj. BAR # automatically call the method defined in the first parameter: get_barobj.BAR = "alex" # automatically call the method defined in the second parameter: set_bar method, and pass "alex" as a parameter to del Foo. BAR # automatically call the method defined in the third parameter: del_bar method obj. BAE. _ doc _ # automatically obtain the value set in the fourth parameter: description...

    Because there are three access methods for creating attributes using static fields, we can define three methods as the same Attribute Based on the access characteristics of these attributes: Get, modify, and delete, the application example is as follows:

Class Goods (object): def _ init _ (self): # original price self. original_price = 100 # discount self. discount = 0.8 def get_price (self): # actual price = original price * discount new_price = self. original_price * self. discount return new_price def set_price (self, value): self. original_price = value def del_price (self, value): del self. original_price PRICE = property (get_price, set_price, del_price, 'price attribute description... ') obj = Goods () obj. PRICE # Get product PRICE obj. PRICE = 200 # modify the original PRICE of the product del obj. PRICE # Delete the original PRICE of a product

4. modifier of Class Members

All the members of the class have been described in detail in the previous step. For each class member, there are two forms:

  • Public members, accessible anywhere
  • Private member, which can be used only within the class

The definitions of private and public members are different.: When a private member is named, the first two characters are underlines. (Except special members, such as __init _, _ call _, and _ dict)

Class C: def _ init _ (self): self. name = 'public field' self. _ foo = "private field"

Access restrictions for private and public members are different.:

Static Field

  • Public static fields: the class can be accessed, the class can be accessed inside, and the class can be accessed in the derived class
  • Private Static Field: accessible only within the class;

Public static field

Class C: name = "public static field" def func (self): print C. nameclass D (C): def show (self): print C. nameC. name # class access obj = C () obj. func () # class internal access obj_son = D () obj_son.show () # class access

Private Static Field

Class C: _ name = "Private Static Field" def func (self): print C. _ nameclass D (C): def show (self): print C. _ nameC. _ name # class access ==> error obj = C () obj. func () # class internal access ==> correct obj_son = D () obj_son.show () # class access ==> Error

If you want to forcibly access private fields externally, you can use [object. _ class name__ private field Description: Access (for example, obj. _ C _ foo). It is not recommended to forcibly access private members.

5. Special members of the class

_ Doc _ indicates the class description.

Class Foo: "Description class information, which is the magic of watching movies" def func (self): passprint Foo. _ doc __# output: class description

_ Module _ and _ class __ 

_ Module _ indicates the module where the object of the current operation is located.

_ Class _ indicates the class of the object for the current operation.

#! /Usr/bin/env python #-*-coding: UTF-8-*-class C: def _ init _ (self): self. name = 'wupeiqi 'from lib. aa import Cobj = C () print obj. _ module _ # output lib. aa: print obj of the output module. _ class _ # output lib. aa. c, that is, the output class

_ Init __

Constructor. It is automatically triggered when an object is created through a class.

Class Foo: def _ init _ (self, name): self. name = name self. age = 18obj = Foo ('hehes') # The _ init _ method in the Automatic Execution class

_ Del __

The Destructor is automatically triggered when an object is released in the memory.

Note: This method is generally not needed to be defined. Because Python is a high-level language, programmers do not need to worry about memory allocation and release when using it, because this job is to be executed by the Python interpreter, the Destructor is automatically triggered by the interpreter during garbage collection.

class Foo:    def __del__(self):        pass

_ Call __

The object is enclosed in parentheses to trigger execution.

Note: The execution of the constructor method is triggered by the creation object, that is, the object = Class Name (). The execution of the _ call _ method is triggered by the brackets behind the object, that is, object () or class ()()

Class Foo: def _ init _ (self): pass def _ call _ (self, * args, ** kwargs ): print '_ call _' obj = Foo () # Run _ init _ obj () # Run _ call __

_ Dict __

All members in a class or object

In the above article, we know that the common fields of the class belong to the object, static fields and methods in the class belong to the class,

Class Province: country = 'China' def _ init _ (self, name, count): self. name = name self. count = count def func (self, * args, ** kwargs): print 'func' # obtain the class members, that is, static fields, methods, and print Province. _ dict __# output: {'country': 'China', '_ module _': '_ main _', 'func ': <function func at 0x10be30f50>, '_ init _': <function _ init _ at 0x10be30ed8>, '_ doc __': none} obj1 = Province ('hebei', 10000) print obj1. _ dict __# obtain the member of the object obj1 # output: {'Count': 10000, 'name ': 'hebei'} obj2 = Province ('henany', 3888) print obj2. _ dict __# obtain the member of the object obj1 # output: {'Count': 3888, 'name ': 'henanc '}

_ Str __

If the _ str _ method is defined in a class, the return value of this method is output by default when an object is printed.

Class Foo: def _ str _ (self): return 'wupeiqi 'obj = Foo () print obj # output: wupeiqi

_ Getitem _, _ setitem _, and _ delitem __

Used for index operations, such as dictionaries. The preceding parameters indicate obtaining, setting, and deleting data respectively.

Class Foo (object): def _ getitem _ (self, key): print '_ getitem _', key def _ setitem _ (self, key, value): print '_ setitem _', key, value def _ delitem _ (self, key): print '_ delitem __', key obj = Foo () result = obj ['k1 '] # automatically triggered execution _ getitem _ obj ['k2'] = 'wupeiqi' # automatically triggered execution _ setitem _ del obj [' k1 '] # automatically triggered execute _ delitem __

_ Iter __

For the iterator, The for loop can be performed for lists, dictionaries, and tuples because _ iter _ is defined in the type __

Step 1

Class Foo (object): passobj = Foo () for I in obj: print I # error: TypeError: 'foo' object is not iterable

Second

Class Foo (object): def _ iter _ (self): passobj = Foo () for I in obj: print I # error: TypeError: iter () returned non-iterator of type 'nonetype'

Third

#!/usr/bin/env python# -*- coding:utf-8 -*-class Foo(object):    def __init__(self, sq):        self.sq = sq    def __iter__(self):        return iter(self.sq)obj = Foo([11,22,33,44])for i in obj:    print i

The above steps show that the for loop iteration is actually iter ([,]), so the execution process can be changed:

#!/usr/bin/env python# -*- coding:utf-8 -*- obj = iter([11,22,33,44]) for i in obj:    print i

For Loop internal syntax

#!/usr/bin/env python# -*- coding:utf-8 -*-obj = iter([11,22,33,44])while True:    val = obj.next()    print val

_ New _ and _ metaclass __

Read the following code:

Class Foo (object): def _ init _ (self): pass obj = Foo () # obj is an object instantiated through the Foo class.

In the above Code, obj is an object instantiated through the Foo class. In fact, not only is obj an object, but the Foo class itself is also an object becauseEverything in Python is an object.

If everything is an object theory: the obj object is created by executing the Foo class constructor, the Foo class object should also be created by executing the constructor of a class.

Print type (obj) # output: <class '_ main __. foo '> indicates that the obj object is created by the Foo class print type (Foo) # output: <type 'type'> indicates that the Foo class object is created by the type class.

So,The obj object is an instance of the Foo class.,The Foo class object is an instance of the type class.That is, the Foo class object is created through the type class constructor.

There are two ways to create a class:

1. Conventional Methods

class Foo(object):     def func(self):        print 'hello wupeiqi'

2. type

Def func (self): print 'Hello wupeiqi 'Foo = type ('foo', (object,), {'func': func}) # The first parameter of type: class Name # type second parameter: base class of the current class # type third parameter: class member

Classes are produced by type class instantiation.

So the question is, the class is generated by the type class instantiation by default. How to Create a class in the type class? How do I create an object?

A: The class has an attribute _ metaclass __, which indicates who will instantiate the class to create. Therefore, we can set a type class derived class for _ metaclass, to view the process of class creation.

Class MyType (type): def _ init _ (self, what, bases = None, dict = None): super (MyType, self ). _ init _ (what, bases, dict) def _ call _ (self, * args, ** kwargs): obj = self. _ new _ (self, * args, ** kwargs) self. _ init _ (obj) class Foo (object): _ metaclass _ = MyType def _ init _ (self, name): self. name = name def _ new _ (cls, * args, ** kwargs): return object. _ new _ (cls, * args, ** kwargs) # Stage 1: The Interpreter executes code from top to bottom to create the Foo class # Stage 2: use the Foo class to create the obj object obj = Foo ()

 

 

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.