python--Class Code writing details

Source: Internet
Author: User
Tags instance method

Class Code writing details

Continue learning classes, methods, and inheritance.

================================================================================

Class statement
The following is the general form of the class statement:

Class <name> (superclass,...):d ata = Valuedef method (self,...): Self.member = value
within a class statement, any assignment statement produces a class attribute, and there is a special name method overload operator. For example, a function named __init__ is called when the instance object is constructed (if defined).
--------------------------------------------------------------------------------------------------------------- -----------------

Example

A class is a namespace, which is a tool that defines a variable name (property).

1. Just like a function, the class statement is a local scope, and the variable name created by the embedded assignment statement exists within the local scope.
2. Just like the variable name within the module, the variable name that is assigned within the class statement becomes a property in the class object.

Because class is a compound statement, any kind of statement can be in its body: print, =, if, Def, and so on. When the class statement itself executes, all statements within the class statement are executed. Variable names that are assigned within a class statement create class properties, and the inline def creates a class method.

For example, assigning a simple non-function object to a class property results in a data property that is shared by all instances.

>>> class Sharedata:spam = 42>>> x = sharedata () >>> y = sharedata () >>> x.spam,y.spam ( 42, 42)
here, because the variable name spam is assigned at the top level of the class statement, it is appended to the class to be shared for all instances. We can modify it by the class name, or it is referenced by an instance or class.

>>> sharedata.spam = 99>>> x.spam,y.spam,sharedata.spam (99, 99, 99)
This class property can be used to manage information across all instances. For example, a counter that produces the number of instances.
Now, if you assign a variable name spam through an instance instead of a class, see what Happens:
>>> x.spam = 88>>> x.spam,y.spam,sharedata.spam (88, 99, 99)
assigning an attribute to an instance creates or modifies a variable name within that instance, rather than in a shared class.
Assigning a value to an object property always modifies the object, except that it has no other effect. For example, Y.spam will look in the class through inheritance, but assigning a value to X.spam will append the variable name to the X-book.


See this example to make it easier to understand this behavior by storing the same variable name in two locations:

>>> class mixednames:data = ' spam ' def __init__ (self,value): Self.data = valuedef display (self):p rint (self.data , Mixednames.data)
when an instance of this class is created, the variable name data is assigned to the Self.data within the constructor method to append data to the instances.
>>> x = mixednames (1) >>> y = mixednames (2) >>> x.display (), Y.display () 1 spam2 spam (none, none)
"Here (None,none) is the return value of the call display function"
As a result, data exists in two places: within the instance object (created by the Self.data assignment operation in __init__) and in the class where the instance inherits the variable name (created by the data assignment operation in the Class). The display method of the class prints the two versions, first taking the property of the self instance with the dot operation, and then the class.

By using these techniques to store attributes within different objects, we can determine their visible range. When attached to a class, the variable name is shared, and when attached to the instance, the variable name is the data that belongs to each instance, not the shared data.
================================================================================

Method

Method is a function. The method in class is a function object created by the DEF statement. From an abstract point of view, the method provides the behavior to inherit from the instance object. From a procedural point of view, the method works exactly like a simple function, with only one important difference: The first parameter of the method always receives the implicit principal of the method call, that is, the instance object.

Python automatically corresponds the invocation of the instance method to the class method function. As shown below, the method invocation needs to pass through the instance, just like this:

Instance.method (args ...)
This is automatically translated into the following form of the class method function call:
Class.method (Instance,args ...)
Class inherits the search process through Python to find out where the method name resides. In fact, both of these invocation forms are valid in Python.

In a class method, by convention The first argument is usually called self (strictly speaking, only its location is important, not its name). This parameter gives the method a hook that returns the body of the call, which is the instance object: Because the class can produce many instance objects, this parameter is required to practice data that each instance differs from each other.
----------------------------------------------------------------------------------------------------------- ---------------------

Example
Define the following class:

>>> class Nextclass:def Printer (self,text): Self.message = Textprint (self.message)
We call the printer method through an instance as follows:
>>> x = Nextclass () >>> X.printer (' instance call ') instance call>>> x.message ' instance call '
When it is called by an instance for a point number operation, printer will first locate it through inheritance, and then its self parameter is automatically assigned to the instance object (x). The text parameter gets the string passed in at the time of invocation (' instance call '). Note: Because Python automatically passes the first argument to self, you actually need to pass only one parameter. In printer, the variable name self is used to read or set the data for each instance, because self refers to the instance that is currently being processed.

The method can be invoked either by an instance or by any of the two methods of the class itself. For example, we can also call printer through the name of the class, as long as we explicitly pass an instance to the self parameter.
>>> nextclass.printer (x, ' Class call ') #Direct class Callclass call>>> X.message ' class call '
Calls through instances and classes have the same effect, as long as the same instance object is passed in the class form. In fact, by default, if you try to invoke a method without any instance, you get an error message.
>>> Nextclass.printer (' Bad call ') Traceback (more recent call last):  File "<pyshell#35>", line 1, in &L t;module>    nextclass.printer (' Bad call ') Typeerror:printer () Missing 1 required positional argument: ' Text '
================================================================================

Calling a superclass constructor

At construction time, Python will find and invoke only one __init__. If the constructor of a subclass is guaranteed to also execute the logic of the superclass construct, it is generally necessary to explicitly call the __init__ method of the superclass through the class.

Class Super:def __init__ (self,x): ... default Code...class Sub (Super):d EF __init__ (self,x,y): super.__init__ (self,x) ... custom code ... I = Sub (UP)
This writing facilitates the maintenance of code, which has been described before. This method extends the method of the superclass rather than completely replacing it.
================================================================================

Class Interface Technology

An extension is just a way to interface with a superclass. The specialize.py file shown below defines several classes, demonstrating some common techniques.

Super: Defines a method function and the delegate of expecting an action in a subclass.
inheritor: No new variable name is provided, so you get everything defined in super.
Replacer: Use your own version to cover Super's method
Extender: Override and callback default method to customize Super's method
Provider: Implements the action method expected by the super delegate method.

Here is the file:

Class Super:    def method (self):        print (' in Super.methon ')    def delegate (self):        self.action () class Inheritor (Super):    Passclass replacer (Super):    Def Method (self):        print (' in Replacer.method ') class Extender (Super):    def Method (self):        print (' starting Extender.method '),        super.method (self)        print (' Ending Extender.method ') class Provider (Super):    def action:        print (' in provider.action ') if __name__== ' __main__ ': for    Klass in (inheritor,replacer,extender):        print (' \ n ' +klass.__name__+ ' ... ')        Klass (). Method ()    print (' \nprovider ... ')    x = Provider ()    x.delegate ()
The results of the implementation are as follows:
Inheritor...in super.methonreplacer...in replacer.methodextender...starting Extender.methodin Super.methonending Extender.methodprovider...in provider.action
================================================================================
Abstract Super Class

Notice how the provider class in the previous example works. When you call the delegate method through an provider instance, there are two independent inheritance searches that occur:

1. In the initial x.delegate call, Python searches the provider instance and its upper-level objects until the delegate method is found in super. Instance x is passed to the self parameter of this method as usual.

2. In the Super.delegate method, Self.action initiates a new independent inheritance search for self and the objects on top of it. Because self refers to a provider instance, the action method is found in the provider subclass.

This "fill-in" code structure is generally the software framework of OOP. The superclass in this example is sometimes referred to as an abstract superclass-that is, the partial behavior of a class is provided by its subclasses by default. If the expected method is not defined in the subclass, Python throws an exception that does not define the variable name when the inheritance search fails.

python--Class Code writing details

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.