In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "summary of common object-oriented knowledge points in Python". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the summary of common object-oriented knowledge points in Python".
0x00 is and = =
The = = operator compares whether the contents of two objects are equal, and the default is to call the _ _ eq__ method of the object to compare, while is compares whether the two objects are the same, the id of the two objects it compares, that is, whether their memory addresses are the same.
> a = [1id (a) 4498717128 > b = [1pje 2je 3] > > a = = whether bTrue# an and b are the same object > an is bFalse# an and b are actually different addresses > id (a) 4498717128 > id (b) 4446861832
In comparison, but there are exceptions. Python optimizes the cache of some commonly used values, such as integers in the range [- 5256]. When they are created, no matter how many objects are created, their id is the same, that is, they keep only one copy of memory in the underlying layer.
> > a =-5 > > b =-5 > a = = bTrue > > an is bTrue > a =-6 > b =-6 > a = = bTrue > an is bFalse
The same is true for some short strings, so not all strings create new instances
> > a==bTrue > > an is bTrue > id (a) 4446903800 > id (b) 4446903800 > > x = 'long char' > y =' long char' > > x = = yTrue > x is yFalse
0x01 _ _ repr__ and _ _ str__
Each class should provide a _ _ repr__ method. What is the difference between the _ _ repr__ method and the _ _ str__ method?
To put it simply, _ _ repr__ can reflect the type and content of an object, while _ _ str__ is mainly used to print the content of an object. For example, look at the date class datetime in Python
Import datetime > > today = datetime.date.today () > > todaydatetime.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 concatenation, printing and other operations, while _ _ repr__ is mainly for developers, and it can provide a lot of feedback. For example, entering today in an interactive environment will print out datetime.date (2019, 7, 7). You can see not only that today represents today's date information, but also its type information. More importantly, you can directly copy this printed message and directly construct an "identical" object.
For example
> now = datetime.date (2019, 7, 7) > nowdatetime.date (2019, 7, 7)
0x02 object replication
Object replication or object copy can be divided into shallow copy and deep copy.
Shallow copy and deep copy
If we explain it through the code, it's easy to understand.
If the object to be copied is a basic data type, there is not much difference between a deep copy and a shallow copy.
> a = [1pr 2pr 3] > > b = list (a) > > a [1] = 200,200 > > a [1,200,3] > > b [1Jing 2jue 3]
Modifying the elements in a does not affect b
But if the object you want to copy contains another object, consider deep copy and shallow copy.
> a = [1 list 2 rect 3], [4 recorder 5 recorder 6], [7 recorder 8 recorder 9] > > b = bTrue (a) > > a = = bTrue > > an is bFalse
Here is a list a with three sublists, that is, the list contains objects.
We use the list factory method to create a copy b of a, which 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 there is no copy of the sub-object, only a reference to the sub-object.
If you know the shallow copy, it is easy to understand the deep copy. After the copy is performed, the copy object and the original object are completely independent, and modifying either object will not affect the other object.
How to deeply copy an object
At this point, you need the copy module, which has two important methods, deepcopy and copy. Yes, it stands for deep copy and shallow copy, respectively.
> > import copy > a = [1pje 2 import copy 3], [4pje 5 change' 9] > > b = 5 change' (a) > > a [1 pr 2 pas 3], [4pr 5 change' 6], [7 mei 8 change' 9] > > b [1] [2] = 'change' > > a [1] [1], [4 pint 5,' change'], 9] > > b [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
After performing a deep copy, changes to a do not affect b.
0x03 Abstract Base Classes (ABC)
The use of abstract base classes
To explain why you use ABC, let's take a look at the situation where you don't use ABC
# defined base class Base > > class Base: def foo (self): raise NotImplemented def bar (self): raise NotImplemented# definition implementation class > class Concrete (Base): def foo (self): print ('called foo') # implementation class does not implement bar methods > c = Concrete () > > c.foo () Called foo > > c.bar () Traceback (most recent call last): File "" Line 1, in c.bar () File "", line 5, in bar raise NotImplementedTypeError: exceptions must derive from BaseException
You can see that the Concrete class that does not implement the base class bar method can still be used without throwing an error in the first place.
To solve this problem, we need to use our abc module.
From abc import ABC# defines the base class Inherited from ABC > class Base (ABC): @ abstractmethod def foo (self): pass @ abstractmethod def bar (self): pass > class Concrete (Base): def foo (self): print ("called foo") # the implementation class does not implement the bar method > c = Concrete () Traceback (most recent call last): File ", line 1 In c = Concrete () TypeError: Can't instantiate abstract class Concrete with abstract methods bar
As you can see, when you use the Concrete constructor, the TypeError is thrown immediately.
Benefits of using namedtuple for 0x04
The use of namedtuple is also mentioned in the previous article, "how to represent an object in Python."
To put it simply, namedtuple is a nameable tuple, it is an extension of tuple, it has the same immutable properties as tuple.
For the definition of some data classes, namedtuple is very convenient to use
> from collections import namedtuple > Point = namedtuple ('Point','x y z') > p = Point (1meme3) > pPoint (xylene 1, yellow3, zodiac 5) > > p.x1 > p.y = 3.5AttributeError: can't set attribute# can see that an object defined by namedtuple is a class type > type (p).
You can also use some of its internal tools and methods, which are also very practical in actual coding.
# convert to dict > > p._asdict () OrderedDict ([(('x, 1), ('y, 3), ('z, 5)]) # Update or replace an attribute value > p._replace (x = 111) Point (x = 111, y = 3, z = 5) # create a new object using _ make > Point._make ([333666999]) Point (x = 333, y = 666, z = 999)
0x05 class variables and instance variables
The attribute types of objects in Python are instance variables and class variables.
The class variable belongs to the 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, it is not in the "memory space of the class", it is independent 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_legs4
A cat is defined here, which has an instance variable name and a class variable num_legs, which is shared by all instances.
If you make a class variable, other instances will also be modified synchronously. On the other hand, the modification to an instance does not affect the class variables.
> Cat.num_legs = 6 > tom.num_legs,jack.num_legs (6,6) > tom.num_legs = 2 > tom.num_legs,jack.num_legs (2,6) > Cat.num_legs6
The statement tom.num_legs = 2 actually adds an attribute to the instance of tom, except that the attribute name is the same as the name of the class property.
0x06 instance methods, class methods, and static methods
To make a better distinction, let's look at the code.
> > class MyClass: def method (self): print (f "instance method at {self}") @ classmethod def classmethod (cls): print (f'classmethod at {cls}') @ staticmethod def staticmethod (): print ('staticmethod') > mc = MyClass () > > mc.method > > mc.classmethod > mc.staticmethod
You can see that instance methods (method), class methods (classmethod), and static methods (staticmethod) are defined in MyClass.
Everything is an object in Python, so I print the _ _ repr__ output of 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.
> mc.method () instance method at > MyClass.method (mc) instance method at
Both class method calls and static method calls use ClassName.methodName ().
> MyClass.classmethod () classmethod at > MyClass.staticmethod () staticmethod
What's the difference between class methods and static methods?
First of all, you can see that the object of the class method is different from the static method, one is bound method, the other is function.
Second, class methods can access the class object MyClass, while static methods cannot.
In the end, a static method is actually the same as a normal function object, except that it belongs to the class namespace.
0x07, sum up.
This article mainly explains some common object-oriented features in Python. It includes comparison, output, copy and other operations of 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.
Thank you for your reading, the above is the "summary of common object-oriented knowledge points in Python", after the study of this article, I believe you have a deeper understanding of the problem of summarizing the common object-oriented knowledge points in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.