What you should know about object oriented in Python

  • 2021-07-13 05:44:40
  • OfStack

0x00 is and = =

The = = operator compares the contents of two objects for equality, by default calling the object's __eq__ method for comparison; While is is to compare whether two objects are 1 sample, it compares the id of two objects, that is, whether their memory addresses are the same.


>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True
# a And b Whether it is the same 1 Objects 
>>> a is b
False
# a And b The address of is actually no 1 Like 
>>> id(a)
4498717128
>>> id(b)
4446861832

In comparison, there are exceptions. Python caches a number of commonly used values, such as integers in the interval [-5,256]. When they are created, no matter how many objects are created, their id is like 1, that is, they only hold one share of memory in the bottom layer.


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False

The same is true for 1 short strings, so not all strings will be created with new instances


>>> a='123'
>>> b='123'
>>> a==b
True
>>> a is b
True
>>> id(a)
4446903800
>>> id(b)
4446903800
>>> x = 'long char'
>>> y = 'long char'
>>> x == y
True
>>> x is y
False

0x01 __repr__ and __str__

Each class should provide 1 __repr__ method. What is the difference between the __repr__ method and the __str__ method?
Simply put, __repr__ can reflect the type and content of an object, while __str__ is mainly used to print the contents of an object. For example, look at the date class datetime in Python under 1


import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2019, 7, 7)
>>> print(today)
2019-07-07
>>> str(today)
'2019-07-07'
>>> repr(today)
'datetime.date(2019, 7, 7)'

__str__ is used in string connection, printing and other operations, while __repr__ is mainly for developers, and it can feed back more information. For example, entering the variable today in interactive environment will print datetime. date (2019, 7, 7), which not only shows that today represents today's date information, but also shows its type information. More importantly, you can directly copy the printed information and construct an "identical" object.

For example


>>> now = datetime.date(2019, 7, 7)
>>> now
datetime.date(2019, 7, 7)

0x02 Object Replication

Object copy or object copy can be divided into shallow copy and deep copy.

Shallow copy and deep copy

We explain it through code, which is easy to understand

If the object to be copied is a basic data type, there is not much difference between deep copy and shallow copy.


>>> a = [1,2,3]
>>> b = list(a)
>>> a[1]=200
>>> a
[1, 200, 3]
>>> b
[1, 2, 3]

Modifying elements in a does not affect b

However, if the object to be copied contains another object, then the problem of deep copy and shallow copy should be considered.


>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> b = list(a)
>>> a == b
True
>>> a is b
False

Here is a list a, which has three sub-lists, that is, the list contains objects.

We used the list factory method to create a copy of a, b. This b is a shallow copy of a. Why?


>>> a[1][2]='x'
>>> a
[[1, 2, 3], [4, 5, 'x'], [7, 8, 9]]
>>> b
[[1, 2, 3], [4, 5, 'x'], [7, 8, 9]]

The element of a [1] [2] is changed to x, and the same change is responded to in the b list. So this is a shallow copy, because the child object is not copied, only the reference to the child object is copied.

If you know the shallow copy, then the deep copy is easy to understand. After copying, the copied object and the original object are completely independent, and modifying any one object will not affect the other

How to Deep Copy an Object

This is where you need the copy module, which has two important methods, deepcopy and copy. Yes, it means deep copy and shallow copy respectively.


>>> import copy
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> b = copy.deepcopy(a)
>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a[1][2]='change'
>>> a
[[1, 2, 3], [4, 5, 'change'], [7, 8, 9]]
>>> b
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

After deep copying, the changes to a do not affect b.

0x03 Abstract Base Classes(ABC)

Use of abstract base classes

To illustrate why you want to use ABC, let's first look at the situation where you don't use ABC


#  The base class is defined Base
>>> class Base:
	def foo(self):
		raise NotImplemented
	def bar(self):
		raise NotImplemented

#  Defining Implementation Classes 
>>> class Concrete(Base):
	def foo(self):
		print('called foo')
  
  #  The implementation class does not implement the bar Method 
	
>>> c = Concrete()
>>> c.foo()
called foo
>>> c.bar()
Traceback (most recent call last):
 File "<pyshell#391>", line 1, in <module>
  c.bar()
 File "<pyshell#384>", line 5, in bar
  raise NotImplemented
TypeError: exceptions must derive from BaseException

You can see that the Concrete class, which does not implement the bar method of the base class, can still be used without throwing an error in time 1.

To solve this problem, we will use our abc module.


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
0

You can see that when you use the Concrete constructor, the TypeError is thrown immediately.

0x04 Benefits of using namedtuple

The usage of namedtuple is also mentioned in the previous article "How to represent an object in Python".

Simply put, namedtuple is a nameable tuple, which is an extension of tuple and has immutable properties like tuple1.

namedtuple is very convenient to use for the definition of one data class


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
1

You can also use one of its internal tools and methods, which are also very practical in actual coding.


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
2

0x05 class variables and instance variables

The attribute types of objects in Python are instance variables and class variables.

A class variable belongs to a class. It is stored in the "memory space of the class" and can be shared by its various instance objects. The instance variable belongs to a specific instance, which is not in the "memory space of the class", but exists independently of each instance.


>>> class Cat:
	num_legs = 4
	
>>> class Cat:
	num_legs = 4
	def __init__(self,name):
		self.name = name

>>> tom = Cat('tom')
>>> jack = Cat('jack')
>>> tom.name,jack.name
('tom', 'jack')
>>> tom.num_legs,jack.num_legs
(4, 4)
>>> Cat.num_legs
4

Here, a cat is defined with an instance variable name and a class variable num_legs, which is shared by all instances.

If you do it on class variables, other instances will be modified synchronously. However, modifying an instance pair does not affect all class variables.


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
4

The statement tom. num_legs = 2 actually adds an attribute to the instance tom, except that the name of the attribute matches the name of the class attribute.

0x06 Instance Methods, Class Methods, and Static Methods

For better differentiation, let's look at the code


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
5

You can see that instance methods (method), class methods (classmethod), and static methods (staticmethod) are defined in MyClass

In Python, 1 is an object, so I print the __repr__ output for each method.

The instance method method is bound in the concrete implementation object of MyClass, while the class method classmethod is bound in MyClass, while the static method staticmethod is neither bound in the instance nor in the class. It is the call of an instance method of function object, which needs to pass an instance object to the instance method. The calls of the following two methods are equivalent.


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
6

Class method calls and static method calls are made using ClassName. methodName ().


>>> a = -5
>>> b = -5
>>> a == b
True
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a == b
True
>>> a is b
False
7

What is the difference between a class method and a static method?

First of all, you can see that the objects of class methods and static methods are different, one is bound method, and the other is function. Second, class methods can access the class object MyClass, while static methods cannot. Finally, the static method is actually like an ordinary function object 1, except that it belongs to the class namespace.

0x07 Summary 1

This article mainly to Python 1 some common object-oriented related 1 some characteristics are explained. This includes operations such as comparing, outputting, and copying objects, as well as the recommended use of namedtuple to define data classes. Finally, the differences between class variables and instance variables, as well as class methods, instance methods and static methods are analyzed.


Related articles: