python class in those tips, snowball season finale

Posted by skatermike21988 on Tue, 12 Oct 2021 01:38:18 +0200

This blog brings you some tips in python class, which can improve your efficiency.

Magic method__ str__ And__ repr__

  • __ str__: This method is called when an object is converted to a string.
  • __repr__:

The two methods need comparative learning because their functions are very similar.

class Student(object):
    def __init__(self, name):
        self.name = name


# Print class using print
s = Student("eraser")
print(s) # <__main__.Student object at 0x0000000000547710>

The above code uses print to print the class and finds that the memory address of the class object is directly output.
If you add a magic method to a class__ str__, Customized output can be realized.

class Student(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "This is a student class. Your name is:" + self.name


# Print class using print
s = Student("eraser")
print(s)  # This is a student class. Your name is: eraser

__ repr__ And__ str__ The effect of the implementation is basically the same, and it is also to convert the object into a string in some cases.

__ repr__ The scenarios that occur can be tested through the following steps (ignoring exceptions and forgetting to pass parameters during instantiation).

You can directly call the s object in the console to view it__ repr__ method.
If you want manual control__ str__ And__ repr__ Method, which can be implemented by str() and repr() functions.
Used in general industry__ repr__ Method to output meaningful strings to developers.

If not used in class__ str__ Method, using only__ repr__ Method, which will be called automatically when the program runs__ repr__ method.

Shallow replication and deep replication

Deep copy and shallow copy are actually concepts derived from python cloned objects. Shallow copy only copies the first layer of the object. Deep copy copies the entire object tree. The concepts are not easy to distinguish. You can directly view the code.
Shallow replication

my_list1 = [[1, 2, 3], ["a", "b", "c"]]
my_list2 = list(my_list1)
print(my_list2)  # Shallow copy, output [[1, 2, 3], ['a ',' B ',' C ']]
my_list1.append([4, 5, 6])  # Give it to my_list1 append element
print(my_list2)  # my_list2 is not affected, output [[1, 2, 3], ['a ',' B ',' C ']]

# However, since shallow copy only copies the first layer, if you modify my_ Elements in LIST1
my_list1[0].append(666)
print(my_list2)  # my_ The first item in List2 is affected, output [[1, 2, 3, 666], ['a ',' B ',' C ']]

If deep replication is performed, the two objects will be completely independent. Deep replication is implemented using deepcopy() of the copy module.

from copy import deepcopy

my_list1 = [[1, 2, 3], ["a", "b", "c"]]
my_list2 = deepcopy(my_list1)
print(my_list2)  # Deep copy, output [[1, 2, 3], ['a ',' B ',' C ']]
my_list1.append([4, 5, 6])  # Give it to my_list1 append element
print(my_list2)  # my_list2 is not affected, output [[1, 2, 3], ['a ',' B ',' C ']]

my_list1[0].append(666)  # Deep copy copies only the whole number of objects. If you modify my_ Elements in LIST1
print(my_list2)  # my_list2 will not be affected, output [[1, 2, 3], ['a ',' B ',' C ']]

The copy method in the copy module is shallow copy.

Using namedtuple to define classes

namedtuple, like ordinary tuples, is an immutable data type. It is generally called a tuple with a name. Its elements can be accessed through a unique identifier without using an integer index. It can also be used to define classes. The specific implementation is as follows:

from collections import namedtuple

Student = namedtuple('Student', ["name", "age"])

The first parameter of the namedtuple function represents the name of the newly created class, and the second parameter is the attribute name in the class, which can be list or string, but different attributes need to be separated by spaces.

Create an object using Student. The code is as follows:

from collections import namedtuple

Student = namedtuple('Student', ["name", "age"])

s1 = Student("eraser", 18)
print(s1.name)
print(s1.age)
print(s1) # Student(name = 'eraser', age=18), you can see that it is rewritten automatically`__ str__`  method
print(s1.__doc__) # Student(name, age)

Since tuples are immutable, objects cannot be modified after initialization.

s1.name = "Wipe sister" # Error: AttributeError: can't set attribute

namedtuple is implemented internally by python classes, so the classes it creates can be inherited.

from collections import namedtuple

Student = namedtuple('Student', ["name", "age"])

class MidStudent(Student):
    def run(self):
        print(self.name,"gogogo")

s2 = MidStudent("eraser", 18)
print(s2)
s2.run()

The namedtuple class has special properties and methods
_ Fields: get class fields:

from collections import namedtuple

Student = namedtuple('Student', ["name", "age"])

class MidStudent(Student):
    def run(self):
        print(self.name,"gogogo")

s2 = MidStudent("eraser", 18)
print(s2._fields) # Output ('name ',' age ')

_ asdict: return the namedtuple object as a dictionary:

from collections import namedtuple

Student = namedtuple('Student', ["name", "age"])

class MidStudent(Student):
    def run(self):
        print(self.name,"gogogo")

s2 = MidStudent("eraser", 18)
print(s2._asdict()) # OrderedDict([('name ',' eraser '), ('age', 18)])

_ replace: replaces some attribute values in the tuple and returns a shallow copy object

from collections import namedtuple

Student = namedtuple('Student', ["name", "age"])

class MidStudent(Student):
    def run(self):
        print(self.name,"gogogo")

s2 = MidStudent("eraser", 18)
print(s2._replace(name="Wipe sister")) # MidStudent(name = 'wipe sister', age=18)

Class variables and instance variables, class methods and instance methods

Class variables and instance variables
These two concepts need to be studied in comparison. First, let's talk about the concepts:

  • Class variables are declared in the class definition and are not in any class method. Modifying class variables will affect all instances;
  • Instance variables are bound to specific object instances and are not related to each other.

Here is a demonstration of where they appear.

class Student():
    school_name = "Experimental Primary School"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

    def run(self):
        print(self.name, "Running")


s1 = Student("eraser")
s1.age = 18  # Instance variable

The above code uses instance variables in two locations and class variables in one location. If you want to access the above variables, use the following code:

print(s1.name, s1.age)  # Access instance variables
print(s1.school_name)  # Access class variables
print(Student.school_name)  # Access class variables

Class variables can be accessed by using object instance or class name, but instance variables cannot be accessed by class name:

# Wrong presentation
print(Student.name) # abnormal

Next, suppose that s2 Xiaoming has transferred to another school, the code will be modified as follows.

s1 = Student("eraser")
s2 = Student("Xiao Ming")

s2.school_name = "Science and Technology Primary School"  # Xiao Ming transfer

print(s1.school_name)  # The eraser school has not changed
print(Student.school_name) # Class variables do not change

At this time, the problem occurs. Modify the school of the S2 object_ Name, which is reassigned, but does not affect the class variables of Student class. This is in contradiction with the just mentioned that modifying class variables will affect all instances. The reason is s2.school_name means to create an instance variable, but the instance variable just overrides the class variable.

If you want to change the name of the primary school, you need to write the following code:

class Student():
    school_name = "Experimental Primary School"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

    def run(self):
        print(self.name, "Running")


s1 = Student("eraser")
s2 = Student("Xiao Ming")

Student.school_name = "Science and Technology Primary School"

print(s1.school_name)
print(s2.school_name)

In the actual coding process, you often create an instance variable. Because it has the same name as the class variable, it leads to the scene of overwriting the class variable. You need to pay special attention.

Class method and instance method, adding static method
First, create a class that contains the above three methods.

class Student(object):
    # Common method
    def func(self):
        print("I am an example method")

    @classmethod
    def cls_func(cls):
        print("I am a class method")

    @staticmethod
    def sta_func():
        print("I'm a static method")

In the coding process, the most common is the instance method. The method must have a self parameter to represent the instance object. If you want to access the class, you can use self__ class__ Implement the modification of the internal state of the class.

Using the decorator @ classmethod, you can convert a normal method into a class method. The class method does not need the self parameter, but the cls parameter to point to the class itself.

The static method needs to be decorated with the decorator @ staticmethod. It does not need to set self and cls, but any other parameters can be set.

When ordinary instance methods are called, the following code is used:

s = Student()
s.func() # Call normal method

In fact, the above writing method is also a syntax sugar provided by python. Python automatically replaces the object name s with the parameter self position of func method. If the syntax sugar is not used, use the following code to call the instance method.

s = Student()
Student.func(s) # Pass the parameter s to the func method of the Student class

Class name. Method name () is required for calling class methods

Student.cls_func()

For calling static methods, you can use class name. Method name (), or object name. Method name ()

s = Student()
s.sta_func()
Student.sta_func()

However, it should be noted that static methods can neither access instance objects nor classes. It is only the namespace belonging to a class.

Write it at the back

The fourth season snowball learning Python is over!

Today is the 237th / 365 day of continuous writing.
Look forward to attention, praise, comment and collection.

More wonderful

Topics: Python list