A summary of knowledge points about Python object-oriented programming

Source: Internet
Author: User
Python has been an object-oriented language since its inception, which is why it is easy to create a class and object in Python. The following article will give you a detailed introduction to the Python object-oriented programming knowledge points, the need for friends can refer to, let's take a look at it.

Objective

If you have not been exposed to object-oriented programming languages before, you may need to first understand some of the basic features of object-oriented languages and form a basic object-oriented concept in your mind, which will help you learn more about Python's object-oriented programming.

Next, let's learn about Python's object-oriented programming knowledge.

Classes and instances

A class is the definition of an object, and an instance is a "real thing," which holds specific information about the objects defined in the class.

class, attribute, and method naming conventions

Class names are usually preceded by uppercase letters. This is a standard practice that can help you identify classes, especially during instantiation (sometimes it looks like a function call). Also, the data attribute (variable or constant) should sound as the name of the data value, and the method name should indicate the behavior of the corresponding object or value.

Another way to express this is that the data value should use a noun as the name, and the method uses a predicate (verb plus object). A data item is an action object, and the method should indicate what the programmer wants to do with the object.

In the class defined, roughly following the guidelines, data values like "name", "Phone" and "email", behave like "Updatephone", "Updateemail". This is often called "mixed notation (mixedcase)" or "Camel notation (CamelCase)". The Python specification recommends the use of camel notation, such as "Update_phone", "Update_email". class also to be carefully named, like "Addrbookentry", "Repairshop" and so on is a very good name.

Class Addrbookentry (object): Def __init__ (self, name, phone, email): self.name = name Self.phone = Phone Self.email = Emai L def update_phone (self, phone): Self.phone = Phone def update_email (self. email): Self.email = Email

New class and Old class

The biggest difference between a new class and a classic class declaration is that all modern classes must inherit at least one parent class. If there are no classes that can be inherited, you can inherit the object class. Object is the "mother of all Classes", which is at the top of all class inheritance structures. If there is no direct or indirect subclass of an object, then a classic class is defined. That is, if a parent class is not specified, or if the subclass of the base class does not have a parent class, then a classic class is created.

Classes defined in Python3, which are new classes by default, and in Python2 to define a modern class, must inherit object or inherit a new class.

Self variable

There is only one special difference between a method of a class and a normal function, that is, they must have an extra first parameter name, but you do not have to assign a value to this parameter when calling this method, and Python provides this value. This particular variable refers to the object itself, according to the Convention its name is self. Although you can give this parameter any name, it is strongly recommended to use the name self, and the other names are deprecated.

__init__ () method

__init__ () is similar to a class constructor, but is not actually a constructor. After Python creates an instance, it calls the __init__ () method during instantiation, and when a class is instantiated, it is possible to define additional behavior, such as setting an initial value or running some preliminary diagnostic code, mainly after the instance has been created, before the instantiation call returns to the instance. To perform certain tasks or settings.

Binding and non-binding methods

In Python, methods that access a class can be accessed directly through an instance or through a class. But Python is strict, there is no instance, the method cannot be called. This restriction is the binding concept (binding) described by Python, where the method must be bound (to an instance) to be called directly. A non-binding method may be called, but the instance object must be explicitly given in order to ensure that the call succeeds. However, regardless of whether or not it is bound, the method is the intrinsic property of the class in which it resides, even though they are almost always invoked through an instance. The class method in Python is also an object. It is simple to understand that the method of direct access through a class is called an unbound method, whereas a method accessed through an instance is called a "bound method":

1. Unbound class method: no Self

Returns an unbound method object through a class that refers to a method. To invoke it, you must present an instance as the first parameter.

2. Instance of the binding method: Self

Returns a bound method object through the instance access method. Python automatically binds an instance to a method, so we don't have to pass an instance argument when we call it.

Example:

Class Test:def func (self, message): Print Messageobject1 = Test () x = Object1.funcx ("Bind method object, instance is hidden") T = test.funct (object1 , "unbound method object, need to pass an instance") # T ("Unbound method object, need to pass an instance") # Wrong call

Class properties and Instance properties

Class properties are only data values that are related to the class, and are different from instance properties, and class properties are independent of the instance. These values are referred to as static members, and their values remain the same even if the class is called in multiple instantiations. Static members, however, do not change their values because of the instance, unless they are explicitly changed in the instance. Instance properties are compared to class properties, similar to automatic variables and static variables, but this is only a general analogy. Don't delve into these when you're not quite familiar with automatic and static variables.

Both classes and instances are namespaces. The class is the namespace of the Class property, and the instance is the instance property.

Classes can be used to access class properties, which can also be accessed using instances if they do not have attributes of the same name.

Privatization

Python does not directly support private methods, but relies on the programmer to grasp the timing of the external feature modification.

To make a method or feature private (inaccessible from outside), simply precede its name with a double underline. Properties that start with double underlines are "confused" at run time, so direct access is not allowed.

In fact, in Python, properties or methods with double underscores are not private in the true sense, and they can still be accessed. In the internal definition of a class, all names that begin with a double underscore are "translated" into the form preceded by a single underscore and a class name:

>>> class Testobj (object): ... __war = "World" ... def __init__ (self): ... self.__har = "Hello" ... def __f Oo (self): ... print (Self.__har + self.__war) ... >>> t = testobj () >>> dir (t) [' _testobj__foo ', ' _ Testobj__har ', ' _testobj__war ', ' __class__ ', ' __delattr__ ', ' __dict__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' _ _reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ' >>> T.__wartraceback (most recent): File "<input>", line 1, in <module> T.__warattributeerr Or: ' Testobj ' object has no attribute ' __war ' >>> t.__hartraceback (most recent call last): File "<input>", Line 1, in <module> t.__harattributeerror: ' Testobj ' object have no attribute ' __har ' >>> t.foo () Traceback (M OST recent call last): File "<inpUt> ", line 1, in <module> T.foo () attributeerror: ' Testobj ' object has no attribute ' foo ' >>> t._testobj__ War ' World ' >>> t._testobj__har ' hello ' >>> t._testobj__foo () HelloWorld

__slots__ class Properties

Normally, when we define a class and create an instance of class, we can bind any property and method to that instance, which is the flexibility of dynamic language. The default dictionary is used in Python to store the properties of an instance.

Example:

>>> class A (): ... = pass ... >>> a = a () >>> a.name = "Huoty" >>> a.age = 25>>> pr int a.namehuoty>>> Print a.age25>>> a.__dict__{' age ': ' Name ': ' Huoty '}

The dictionary is located in the "heart" of the instance. The __dict__ property tracks all instance properties. For example, you have an instance of Inst, which has a property of Foo, which is consistent using Inst.foo to access it with the use of inst.__dict__[' foo ').

Dictionaries occupy a lot of memory, and if you have a class with a small number of properties, but there are many instances, that's exactly the case. For memory considerations, you can use the __slots__ property to replace __dict__.

, __slots__ is a feature of the new class. Basically, __slots__ is a class variable that consists of a sequence of objects, represented by a collection of instance properties that are composed of all legitimate identities. It can be a list, a tuple, or an object that can be iterated over. It can also be a simple string that identifies the unique properties that an instance can have. Any attempt to create an instance property whose name is not in __slots__ will cause the Attributeerror exception:

>>> class Slotedclass (object): ... __slots__ = ("foo", "Bar") ... >>> C = slotedclass () >>> c. Foo = 42>>> C.bar = "Hello" >>> c.goo = "Don ' t think so" Traceback (most recent call last): File "<inpu T> ", line 1, in <module>attributeerror: ' Slotedclass ' object have no attribute ' goo '

The main purpose of this feature is to conserve memory. The side effect is some type of "security" that prevents users from dynamically adding instance properties as they wish. The class definition with the __slots__ attribute does not exist __dict__ (unless you add the __dict__ element in __slots__).


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.