Summary of knowledge points about Python object oriented programming

  • 2020-05-26 09:27:54
  • OfStack

preface

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

Let's take a look at Python object-oriented programming.

Class and instance

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

Class, attribute, and method naming conventions

Class names are usually started with a capital letter. This is standard practice and can help you identify classes, especially during instantiation (sometimes it looks like a function call). Also, data attributes (variables or constants) should sound like the name of the data value, and method names should indicate the behavior of the corresponding object or value.

Another way to express this is that data values should use nouns as their names and methods should use predicates (verbs plus objects). The data item is the object to operate on, and the method should indicate what the programmer wants to do on the object.

In the defined classes, the guidelines are roughly followed, with data values like "name," "phone," and "email," and behavior like "updatePhone," "updateEmail." This is often referred to as the mixed notation (mixedCase) or the camel notation (camelCase). The Python specification recommends the use of camel notation for underlining, for example, "update_phone", "update_email". The name of the class should also be carefully named, such as "AddrBookEntry", "RepairShop" and so on.


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 class and old class

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

Classes defined in Python3 are new-style classes by default, while classes defined in Python2 must inherit either object or a new-style class.

self variable

Class methods differ from normal functions in only one particular way, that is, they must have an extra first parameter name, but you don't have to assign a value to this parameter when calling this method, Python will provide this value. This particular variable refers to the object itself, which by convention is called self. While you can give this parameter any name, self is strongly recommended, and other names are frowned upon.

__init__ () method

__init__() Similar to a class constructor, but not actually a constructor. After Python has created the instance, during the instantiation, call __init__() Method, when a class is instantiated, you can define additional behavior, such as setting an initial value or running some preliminary diagnostic code, to perform certain tasks or Settings after the instance is created and before the instantiated call returns the instance.

Bound and unbound methods

In Python, methods that access a class can be accessed either by instance or directly by class. But Python is so strict that no method can be called without an instance. This limitation is the binding concept described by Python (binding), where a method must be bound (to one instance) to be called directly. Unbound methods may be called, but instance object 1 must be explicitly given to ensure that the call is successful. However, whether bound or not, a method is an inherent 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 easy to understand that methods accessed directly through a class are called "unbound methods", while methods accessed through an instance are called "bound methods" :

1. Unbound class methods: no self

A method referenced by a class returns an unbound method object. To call it, you must explicitly provide an instance as the first parameter.

2. Binding instance method: has self

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

Example:


class Test:
 def func(self, message):
 print message

object1 = Test()
x = object1.func
x(" Bind the method object, the instance is hidden ")

t = Test.func
t(object1, " Unbound method object that needs to be passed 1 An instance ")
# t(" Unbound method object that needs to be passed 1 An instance ") #  Wrong call 

Class and instance properties

Class attributes are only data values associated with the class, unlike instance attributes, which are independent of the instance. These values are referenced as static members, and their values remain the same even when the class is called in multiple instantiations. However, static members do not change their values from instance to instance unless their values are explicitly changed in the instance. Instance properties are compared to class properties, similar to automatic and static variables, but this is a general analogy. Don't delve into automatic and static variables until you are familiar with them.

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

You can use classes to access class properties, or if the instance does not have a property of the same name.

privatisation

Python does not directly support proprietary methods, but it is up to the programmer to time feature changes externally.

To make a method or property private (not accessible from the outside), simply double underline its name. Properties starting with the double underscore are "confused" at run time, so direct access is not allowed.

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


>>> 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__', '__getat
tribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__
', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> t.__war
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 t.__war
AttributeError: 'TestObj' object has no attribute '__war'
>>> t.__har
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 t.__har
AttributeError: '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 attribute

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

Example:


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

The dictionary is at the "heart" of the instance. __dict__ Property keeps track of all instance properties. For example, you have an instance of inst, which has a property foo, which is used inst.foo To access it and use it inst.__dict__['foo'] Come visit is 1.

Dictionaries take up a lot of memory, and if you have a class with a small number of properties but many instances, that's the case. For memory purposes, can be used __slots__ Properties instead __dict__ .

. __slots__ Is a feature of new-style classes. Basically, __slots__ Is a class variable, consisting of a sequence of 1 objects, represented by a collection of instance properties composed of all valid identifiers. It can be a list, tuple, or iterable object. It can also be a simple string that identifies the 1-only properties that an instance can have. Any attempt to create 1 is not in its name __slots__ The instance properties of the name in the


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

The main purpose of this feature is to save memory. The side effect is a type of "security" that prevents users from dynamically adding instance properties at will. with __slots__ The class definition for the property does not exist __dict__ Unless you are in __slots__ add __dict__ Elements).

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: