Python in several common methods of magic

1, __ init __ () method

  • Initialization method call, called by default when you create an object when an instance is created.
  • __ __ the init () method has a default name for the self parameter, if two passed parameters when creating the object, __init __ () method other self as the first parameter needs two external parameter, e.g. __init __ (self, x, y).

Before we add this attribute to the object:

class Student:
    pass
   
stu1 = Student()

stu1.name = "John Doe"
stu1.age = 18 is

** Now we use __init __ () method to simplify the code **
class Student:
    DEF the __init __ (Self, name, Age):
        the self.name name =
        self.age = Age
   
STU1 = Student ( "Joe Smith", 18)

Is not it more concise code look

2, str () method

  • General description for an object, or a result of their own definition of the desired output.
  • When calling str () calls __str __ (), i.e., the object is cast to a string type.
  • When using the print () output of the object also called __str __ () method, as long as they are defined __str __ () method, it will print the data in this method return.

** not defined __str __ () method when: **
class Student:
    DEF the __init __ (Self, name, Age):
        the self.name name =
        self.age = Age
   
STU1 = Student ( "Joe Smith", 18 is)
Print ( stu1)

s = str(stu1)
print(s)

"""
输出结果:
<__main__.Student object at 0x03C3BCD0>
<__main__.Student object at 0x03C3BCD0>
"""

Is not defined __str __ () method that returns a default memory address of the object.
** defined __str __ () method is such that: **
class Student:
    DEF the __init __ (Self, name, Age):
        the self.name name =
        self.age = Age
    DEF __str __ (Self):
        return "Name:% s \ t Age: D% "% (the self.name, self.age)
   
STU1 = Student (" Joe Smith ", 18 is)
Print (STU1)

s = str(stu1)
print(s)

"" "
Output:
Name: Joe Smith Age: 18
Name: Joe Smith Age: 18
" ""

3, del () method


When an object is deleted, python interpreter will default to a method call, this method is __del __ () method.
 First, it should first understand a concept, it is a reference to the number of objects. We need sys module getrefcount () for measuring an object reference number, a reference to the return value = actual number of +1. 2 to illustrate the actual return when the reference to the object number is one, then there is a reference to the object is variable.
SYS Import
class A:
    Pass
a = A ()
# now only variable a reference to the created object class A
Print (sys.getrefcount (a))
"" "
Output:
2
" ""
# So now to create a variable b , also cited in a reference object, then it will be added to a reference number, the actual number of references becomes 2.
B = a
Print (sys.getrefcount (a))
"" "
output:
3
" ""

When the python interpreter is detected, the number of objects actually referenced is 0, the object will be deleted, then there would be a corresponding call __del __ () method. Another case is that the program has been fully implemented over, then the corresponding memory will be freed, it will execute __del __ () method.
This is the case the program is normally completed execution:
Import SYS
class A:
    DEF __del __ (Self):
        Print ( "the object is destroyed")
A = A ()
"" "
Output:
the object is destroyed
" ""

There is also a case where the variable reference manually remove:
Import SYS
class A:
    DEF __del __ (Self):
        Print ( "the object is destroyed")
A = A () # At this time the number of actual references. 1
B = A # this If the number is actually referenced 2

print ( "deleted variable A")
del A # delete variables a, when the actual number of reference 1

print ( "deleted variable b")
del b # delete variable b, then the actual reference number is 0, python interpreter will remove the object, that is invoked __del __ () method
print ( "End of program")
" ""
output:
delete the variable a
deleted variable b
the object is destroyed
end of program
. "" "

4, new () method

• __new __ class method is called when instance is created, it even earlier than the time __init __ call.
• __new __ CLS have at least one parameter, representative of the class to be instantiated, this parameter is automatically provided by the python interpreter at instantiation.
• __new __ must have a return value, return to instantiate an instance of it, and this point in time to achieve their own __new__ pay special attention to, can return instance of the parent class __new__ out, or is the object of direct __new__ out examples. In Python3 each class of object inherits the default parent class.
• __init__ parameter has a self, is an example of the return __new__, __ init__ can do some other initialization operations on the basis __new__, __ init__ no return value
class A:
    DEF the __init __ (Self):
        Print ( "call the init method")

    __ __new DEF (CLS):
        Print ( "calls the new method")
        return Super () .__ new __ (CLS)
A = A ()

"" "
Output:
call the new method
calls the init method
." ""

4, Development: __ __new can override methods to achieve a single embodiment mode code as follows:

A class:
    # defines a private attribute class, for storing instances of objects out
    _isinstance = None
   
    DEF __new __ (CLS):
        Print ( "calls the new method")
        # determines if _isinstance is None, create an instance, otherwise returned directly _isinstance
        IF not cls._isinstance:
            cls._isinstance = Super () .__ new new __ (CLS)
        return cls._isinstance


print(id(A))
print(id(A))
print(id(A))
print(id(A))
"""
输出结果:
19888488
19888488
19888488
19888488
"""

5, __ slots __ attribute we all know python is a dynamic language, you can add properties while the program is running. How to do if we want to limit the properties of the instances? For example, adding only the name and age of the Person instance attributes. To reach the destination time limit, Python allows the definition of class time, the definition of a special ⼀ __slots__ variable to limit the class instance attributes can be added:

class Person(object):
    __slots__ = ("name", "age")
P = Person()
P.name = "⽼王"
P.age = 20
P.score = 100

"""
输出结果:
Traceback (most recent call last):
  File "<input>", line 6, in <module>
AttributeError: 'Person' object has no attribute 'score'
"""

Note: Use __slots__ pay attention, __ slots__ defined attributes for only the current instance of the class from the Use of submenus class inheritance is not work of Use.

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160212.htm