python classes and objects, __init__(self), __new__(cls, *agrs, **kwargs), object attributes, __del__()

classes and objects

kind

  • class: a collection of objects with the same properties and methods;

  • Object: everything is an object;

  • grammar:

  • #class class name:
     #Attributes
     #method
  • Define a class:
  • class Person:
        def eat(self):
            print("Eating");
        def sleep(self):
            print("Sleeping");
  • class Student: # The name of the class cannot use characters other than underscores, cannot start with numbers, and separate words by upper and lower case
        pass# is used to ensure proper integrity and semantic integrity

Attributes:

  • Concept: members used to access class fields;
  • Attribute use: to ensure the security of data, for data verification;
  • Attribute name: use a noun, describe the operation object, lowercase the first letter, separate words with uppercase letters
  • Method name:
  • Use a predicate (verb + object) to state what operation is performed on what object
  • first letter lowercase
  • separate words with capital letters
  • updatePhone、a
  • Properties are global relative to the class, and each method can be called;
  • Attribution of attributes: class attributes and object attributes
  • When the property is written outside the class, it is called by the method of object.property, object.method()

  • The three elements of an object: properties (what the object is), methods (what the object can do), and events (how the object responds)

  • Interrelationship: A class is an abstraction of an object, an object is an instance of a class, a class is a classification of abstract things, and an object is an instance;

  • There are two ways to create object properties:
  • 1. self: the carrier of the object
  • class Student:
        def __init__(self,name,age):
            self.name=name;
            self.age=age;
        def showName (self):
            print("My name is {}".format(self.name));
    zhangsan=Student('Zhang San',30);
    zhangsan.showName();
  • 2. Created by object.property()
  • class Student:
        def showName (self):
            print("My name is {}".format(self.name));
    zhangsan=Student();
    zhangsan.name='Zhangsan';
    zhangsan.showName();
  • class Student:
        def showName (self):
            print("My name is {}".format(self.name));
    zhangsan=Student();
    zhangsan.name='Zhangsan';
    zhangsan.name='ok';#The second value will overwrite the first value
    zhangsan.showName();

__init__(self): The system automatically calls the initialization method, first generates the object, then calls this method, and then assigns the object to the reference name

  • class Person:
        def __init__(self,name,age):
            self.name=name;
            self.age=age;
            print("Called when init is executed");
    p=Person("ok",20);
    print(p.name);
    print(p.age);
    #Results of the:
    # Called when init is executed
    #ok
    #20

__new__(cls,*agrs,**kwargs): When a class calls the init method, the new method decides whether to use the init method, because new can call methods of other classes, or return other objects as instances of this class;

  • Features of the new() method:

  • The new() method is called when the class is ready to instantiate itself;

  • The new() method is always a static method of the class, even if it is not decorated with a static method;

  • class Student:
        def __new__(cls, *args, **kwargs):
            print("Execute __new__",args[0],args[1]);
            return object.__new__(cls);#fixed syntax
        def __init__(self,name,age):
            print("Execute __init__",name,age);
            self.name=name;
            self.age=age;
        def showName (self):
            print("姓名:{}".format(self.name));
    zhangsan=Student("Zhang San",22);
    zhangsan.showName();

Object Properties: Private and Public

  • If there are some properties that you do not want to be accessed or modified by external permissions, you can add two underscores __ before the name of the property or method, indicating that the object properties are private properties. ValueError is returned when the property is called externally.

  • class Person(object):
        def __init__(self, name):
            self.name = name;
            self._title = 'Mr';
            self.__job = 'Student';#"__" is declared as a private property
    p = Person('Bob');
    print (p.name);
    print (p._title);
    print (p.__job);

package

  • 1. Privatization
  • 2. Set the get() set() method
  • get() and set()
  • class Student:
        def __new__(cls, *args, **kwargs):
            print("Execute __new__",args[0],args[1]);
            return object.__new__(cls);#fixed syntax
        def __init__(self,name,age):
            print("Execute __init__",name,age);
            self.name=name;
            self.__age=age;
        def getAge(self):
            return self.__age;
        def setAge(self,age):
            if age<0 or age>100:
                self.__age=18;
            else:
                self.__age=age;
        def showName (self):
            print("姓名:{}".format(self.name));
    zhangsan=Student("Zhang San",20);
    print('His age',zhangsan.getAge());
    zhangsan.setAge(40);
    print('His age',zhangsan.getAge());

__del__(): automatic destruction method

  • class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        def __del__(self):
            print("Object Zhang San is destroyed")
    zhangsan = Person("Zhang San", 20)
    zhangsan.__del__();

Test how many times an object is referenced: import sys (written at the top of the editor to import packages)

  • Syntax: sys.getrefcount(t) returns from 2
  • import sys#This line of code needs to be written in the head of the editor
    class Person:
        def __init__(self,name,age):
            self.name=name;
            self.age=age;
    zhangsan=Person("Zhang San",20);
    print (sys.getrefcount (zhangsan));

Accessing private attributes can be accessed through the object._classname__ attribute (this method is not recommended)

The id() function checks the memory address of the object: print(id());

Class attributes: belong to class members and are common to objects;

  •  Class method: cls indicates that it is a class

  • Add the @classmethod decorator on the method

  • def class_method(cls):

  • Class properties can be invoked through class methods, and class properties can also be invoked through objects;

  • There are 2 ways to modify class attributes: 1. Class name. Class attribute =... 2. Instance object __class__ class attribute =...

  • Static method: add @staticmethod in front , static method can add parameters, has nothing to do with class and object, and can also be called through class and object;

  • class Person:
        @staticmethod
        def goHome(self, name, by):
            print(name, "回家...", by)
    Person.goHome("1","ok","bicycle");

dir() : Displays the internal properties and functions of a class/object

 __dir__ : Displays the internal properties and functions of a class/object

  • print(dir(zhangsan));
    print(zhangsan.___dir___());

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325440992&siteId=291194637