Summary of Python object-oriented programming knowledge points, python Object-Oriented Programming

Source: Internet
Author: User

Summary of Python object-oriented programming knowledge points, python Object-Oriented Programming

Preface

If you have never been familiar with object-oriented programming languages before, you may need to first understand some basic features of object-oriented languages and form a basic object-oriented concept in your mind, this helps you learn Python object-oriented programming more easily.

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

Class and instance

A class is the definition of an object, and an instance is a "real object". It stores the specific information of the objects defined in the class.

Class, attribute, and method naming rules

The class name is usually prefixed with uppercase letters. This is a standard practice that helps you identify classes, especially during instantiation (sometimes it looks like a function call ). Also, the data attribute (variable or constant) should sound like the name of the data value, and the method name should indicate the behavior of the corresponding object or value.

Another expression is: the data value should use a noun as the name, and the method uses a predicate (verb plus object ). A data item is the object to be operated on and the method should indicate what operations the programmer wants to perform on the object.

The defined classes generally follow this rule. data values are like "name", "phone", and "email", such as "updatePhone" and "updateEmail ". This is often referred to as "mixedCase" or "camelCase )". In Python, we recommend that you use an underscore (_) in the camel notation, for example, "update_phone" and "update_email ". The class should also be well named, such as "AddrBookEntry" and "RepairShop.

class AddrBookEntry(object): def __init__(self, name, phone, email): self.name = name self.phone = phone self.email = email def update_phone(self, phone): self.phone = phone def update_email(self. email): self.email = email

New and old types

The biggest difference between a new class and a classic class declaration is that all new classes must inherit at least one parent class. If no class can be inherited, the object class can be inherited. Object is the mother of all classes. It is located at the top of all class inheritance structures. If an object is not directly or indirectly subclass, a classic class is defined. That is, if no parent class is specified, or if the basic class of the subclass has no parent class, a classic class is created.

Classes defined in Python3 are new classes by default. to define a new class in Python2, you must inherit objects or inherit a new class.

Self variable

There is only one special difference between class methods and common functions, that is, they must have an additional first parameter name, but you do not need to assign a value to this parameter when calling this method, python provides this value. This special variable refers to the object itself, which is named self by convention. Although you can give this parameter any name, we strongly recommend that you use the self name. Other names are not in favor of this name.

_ Init _ () method

__init__()Similar to the class constructor, but it is not actually a constructor. After Python creates an instance, it calls__init__() When a class is instantiated, additional behaviors can be defined, such as setting the initial value or running some preliminary diagnostic code. This is mainly after the instance is created, before the instance is returned for an instantiated call, some specific tasks or settings are executed.

Binding and non-binding methods

In Python, the methods of the classes class can be accessed through instances or classes. However, Python strictly requires that methods cannot be called without instances. This restriction is the binding concept described in Python. Here, the method must be bound (to an instance) to be called directly. A non-bound method may be called, but the instance object must be explicitly specified to ensure the call is successful. However, methods are inherent attributes of their classes regardless of whether they are bound, even if they are almost always called through instances. Class methods in Python are also an object. It can be simply understood that the method for direct access through a class is called "unbound method", while the method for access through an instance is called "binding method ":

1. Unbound class method: No self

A class is used to reference a method to return an unbound method object. To call it, you must explicitly provide an instance as the first parameter.

2. Bound instance method: self

Returns a bound method object through the instance access method. Python automatically binds a method to an instance, so we do not need to pass another instance parameter when calling it.

Example:

Class Test: def func (self, message): print messageobject1 = Test () x = object1.funcx ("bind method object, instance is hidden") t = Test. funct (object1, "No method object bound, need to pass an instance") # t ("No method object bound, need to pass an instance") # incorrect call

Class attributes and instance attributes

The class attribute is only the data value related to the class. It is different from the instance attribute and has nothing to do with the class attribute. These values are referenced as static members. Even if the class is called multiple times, their values remain unchanged. In any case, static members do not change their values because of the instance, unless they explicitly change their values in the instance. The Comparison Between instance attributes and class attributes is similar to automatic variables and static variables, but this is just a general analogy. If you are not familiar with automatic variables and static variables, do not go into these details.

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

You can use a class to define the class attributes. If an instance does not have an attribute of the same name, you can also use an instance to access the instance.

Private

Python does not directly support private methods, but it depends on the programmer's own grasp of the time for external feature modification.

To change a method or feature to private (inaccessible from external sources), you only need to add a Double underline before its name. Attributes starting with double underscore _ are "confused" during runtime, so direct access is not allowed.

In fact, attributes or methods with double underscores in Python are not really private, and they can still be accessed. In the internal definition of a class, all names starting with double underscores are "translated" into the form of a single underline and a class name before them:

>>> class TestObj(object):... __war = "world"... ... def __init__(self):...  self.__har = "hello"...  ... def __foo(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 call last): File "<input>", line 1, in <module> t.__warAttributeError: 'TestObj' object has no attribute '__war'>>> t.__harTraceback (most recent call last): File "<input>", line 1, in <module> t.__harAttributeError: 'TestObj' object has no attribute '__har'>>> t.foo()Traceback (most 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 attributes

Under normal circumstances, when we define a class and create a class instance, we can bind any attributes and methods to the instance, which is the flexibility of Dynamic Language. In Python, the instance attributes are stored in dictionaries by default.

Example:

>>> class A():... pass... >>> a = A()>>> a.name = "huoty">>> a.age = 25>>> print a.namehuoty>>> print a.age25>>> a.__dict__{'age': 25, 'name': 'huoty'}

The dictionary is located in the "heart" of the instance ". __dict__Property tracks all instance properties. For example, you have an instance named inst, which has a property foo.inst.foo To access and use it.inst.__dict__['foo'] Is consistent.

Dictionary occupies a large amount of memory. If you have a class with few attributes but there are many instances, this is the case. For memory considerations, you can use__slots__Attribute to replace__dict__ .

, __slots__ Is a feature of the new class. Basically,__slots__ Is a class variable, which is composed of a series of objects and is expressed by a set of instance attributes consisting of all valid identifiers. It can be a list, tuples, or iteratable objects. It can also be a simple string that identifies the unique attributes that an instance can possess. Any attempt to create__slots__ All instance attributes of the name in will cause AttributeError:

>>> 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 "<input>", line 1, in <module>AttributeError: 'SlotedClass' object has no attribute 'goo'

The main purpose of this feature is to save memory. Its side effect is some type of "security", which can prevent users from dynamically adding instance attributes as they wish. Tape__slots__ Attribute Class definition does not exist __dict__ (Unless you are__slots__ Add__dict__ Element ).

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.