Object-oriented concepts in Python

Source: Internet
Author: User
Tags class definition

Original

Domain and action space

Local region, function domain (nonlocal), and global domain (GLOBALS)

Def scope_test ():    def do_local ():        spam = "Local spam"    def do_nonlocal ():        nonlocal spam        spam = " Nonlocal spam "    def Do_global ():        global spam        spam =" Global spam "    spam =" Test spam "    do_local ()    print ("After local assignment:", spam)    do_nonlocal ()    print ("After nonlocal assignment:", spam)    Do_global ()    print ("After global assignment:", spam) Scope_test () print ("In global scope:", spam)

The result of the output is

After local assignment:test spamafter nonlocal assignment:nonlocal spamafter Global assignment:nonlocal spamIn global S Cope:global spam

* Briefly explain:

The local domain acts on the scope of the current sub-function, the function domain acts on the entire function scope, and the global field acts on the function and outside the function. Priority is the local domain > function domain > Global field.

Basic concepts of classes

The simplest definition of a class looks like this: You can place a class definition in a branch of a if statement, or in a function.

Class ClassName:    <statement-1>    ...    <statement-N>
class properties and initialization methods of the class

Like what:

Class MyClass: "" "    A Simple Example Class" ""    i = 12345    def f (self):        return ' Hello World '

You can assign MyClass.i values to change their values. It __doc__ is also a valid property that returns the docstring that belong to this class: "A simple example class" .

An instantiated operation (called a class object) created an empty object. When you create an instance, many classes may need to have a specific initial state. So a class can define a special method, called __init__() , like this:

>>> class Complex: ...     def __init__ (self, Realpart, Imagpart): ...         SELF.R = Realpart         ... SELF.I = imagpart...>>> x = Complex (3.0, -4.5) >>> X.R, x.i (3.0,-4.5)
Instance Object

What can I do with an instance object? The only operation that can be understood is the property reference. There are two kinds of legal properties, data properties, and methods. (in Python, the concept of a method is not unique to a class instance: Other object types can also have methods.) For example, list objects have methods such as append, insert, remove, sort, and so on. However, in the following discussion, we refer to the method of the class instance object, unless Special note.) (Object not equal to class)

Method Object

Call Method Object

x.f()

In most cases, it is equivalent to call a method (with an n parameter), and call the corresponding function (there are also the N arguments, but add an additional object that uses the method).

When an instance property is referenced, but is not a data property, then its class will be searched. If the name represents a valid class attribute and is a function object, a method object is created by wrapping (pointing to) The instance object, and the function object is still only in the abstract object: This is the method object. When a method object is called with a parameter list, the new argument list is rebuilt from the instance object, and then the function object invokes the new parameter list.

Attention:

Data attributes overwrite the method attribute with the same name; In order to avoid this accidental name conflict, this can lead to difficult-to-find bugs in large programs, and it is wise to use certain naming conventions to minimize conflicts. Possible conventions include uppercase method names, adding a special prefix (or an underscore) before the data type, or using verbs for methods, and data members using nouns.

Inheritance

Definitions of derived classes:

Class Derivedclassname (baseclassname):    <statement-1>    ...    <statement-N>

BaseClassNameDefinition must be visible for derived classes. In the base class, arbitrary expressions are allowed. This can be useful, for example, when a base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Python has two built-in functions for inheritance:

    • Use isinstance() to check the type of an instance: only if it isinstance(obj, int) obj.__class__ is or is a int derived class True .
    • Use the issubclass() inheritance relationship that is used to check the class: It issubclass(bool, int) will be returned True because bool it is a int derived class. However, issubclass(float, int) this is because it is False float not int a derived class.
Multiple Inheritance

Python supports multiple inheritance.

Class Derivedclassname (Base1, Base2, Base3):    <statement-1>    ...    <statement-N>

In an inheritance system, the same class is searched only once. If a property is DerivedClassName not found in, it will search for the Base1, and then (recursively) search Base1 for the base class, and then if it is not found, then it will be searched Base2 , and so on.

Private Variables

In Python, there is no such thing as a "private" variable that cannot be accessed. However, there is a convention in most Python code: a name that takes the lead in an underscore (such as _spam ) should be used as a non-public API (either a function, a method, or a data member). This should be a concrete implementation, and it does not need to be reminded of change.

There is such a mechanism called name mangling. Any identifier, such as a __spam form, (at least two underscores at the beginning) will be replaced with the _classname__spam classname current class. Such processing does not require attention to the syntactic position of the identifier, although it is in the definition of a class.

Data Type

Binds some named data. An empty class definition would be fine:

Class Employee:    Passjohn = Employee () # Create a empty Employee record# Fill The fields of the Recordjohn.name = ' Jo HN Doe ' john.dept = ' computer lab ' john.salary = 1000

In a Python code, if you want an abstract data type, you can pass a class to that method as if you had that data type.

Object-oriented concepts in Python

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.