This post is part of the third session of the Nuggets Creators Training Camp.Digg project | Creator Boot Camp phase 3 is underway, “write” to make a personal impact.

📖 preface

Sanmao once sighed:

“What is the mind like? There is a labyrinth that stretches thousands of miles across. There is no boat that can ferry people. Throughout life, we are learning how to be our own ferrymen.

You can watch this blogger’s article about installation and LocalizationVsCode download, Installation and LocalizationAs well asPython series: windows10 configuration Python3.0 development environment!After installation, restart VsCode!

This article mainly introduces various properties defined in a class, such as class properties, instance properties, private properties of a class, and various methods, such as instance methods, class methods, static methods and property property methods.


🚀 Look at a piece of code

class Tool(object) :
    dog_type = "Huskie"  # class attribute

    def __init__(self,name) :
        self.name = name  # instance attributes
    
    # instance method
    def tell_info(self) :
        pass
    
    # class method
    @classmethod
    def bar(cls) : 
        pass
    
    Static method
    @staticmethod
    def foo(x) :
        pass
    
    # attribute method
    @property
    def tell_name(self) :
        return self.name
Copy the code

Class attributes and instance attributes

Both class attributes and instance attributes are defined in the class, but the fundamental difference is that the location is not the same as the object being called. Such as:

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
"@file: dog.py @time: 2019/10/23 15:00:58@author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


class Dogs(object) :
    # class attribute
    belongTo = "Animals"

    def __init__(self, name) :
        # instance attributes
        self.name = name


dog1 = Dogs("Sunny Chen")
print(Dogs.belongTo)  Class attributes are accessed through classes
print(dog1.name)  Instance properties are accessed by instance
print(dog1.belongTo)  Class attributes can also be accessed by instances
# print(dogs.name) # But the instance attribute is not accessible by the class
Copy the code

Class attributes can be accessed by classes and attributes, whereas instance attributes can only be accessed by instances, due to:

This is because each instance object created through a class will open up a memory space for storing the attributes and methods of the instance object, as well as the Pointers of the class object. The reason why the instance object can call the methods in the class is that the attributes and methods of the class can be accessed through the Pointers of the class object.

However, if the instance object wants to modify the properties and methods of the class, special methods are required. Such as:

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
"@file: dog.py @time: 2019/10/23 15:03:56 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


class Dogs(object) :
    # class attribute
    belongTo = "Animals"

    def __init__(self, name) :
        # instance attributes
        self.name = name


dog1 = Dogs("Sunny Chen")

dog1.belongTo = "wakka"
print(Dogs.belongTo)  #Animals
# Note: Class attributes cannot be modified in this way. Instead, the attribute is overridden in the instance's attribute dictionary
print(dog1.__dict__)  #{'name': 'Sunny Chen', 'belongTo': 'wakka'}

dog1.__class__.belongTo = "Wakka"
print(Dogs.belongTo)  # Wakka-- Changed successfully
Copy the code

Instance methods, class methods, and static methods

Instance method: Usually called by an object, the instance object must be passed in. When the instance method is executed, the instance object itself that called the method is automatically passed to the method’s self argument.

Class methods: Usually called by a class and must be passed in the class object itself. When a class method is executed, the class object calling the method is automatically assigned to the CLS parameter;

Static methods: both class and instance objects can be called, without passing instance and class objects, and without default parameters.

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: testdemo. py @time: 2019/10/23 15:09:21 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


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

    # instance method
    def mm(self) :
        print("in the mm")

    # class method
    @classmethod
    def tt(cls) :
        print("in the tt")
        print(cls)

    Static method
    @staticmethod
    def gg(a) :
        print("in the gg", a)


test1 = Test("alex")
test1.mm()
test1.tt()  
      
test1.gg(100)

Test.mm(test1)  A class object must be passed in to call the instance method
Test.tt()
Test.gg(100)
Copy the code

Similarities: For all methods, they belong to classes (not objects), so only one copy is stored in memory.

Differences: method callers are different, and parameters passed in automatically when calling methods are different.

Class methods and static methods:

Class methods: Mainly use class methods to manage class properties, whether private or ordinary. In many classes, it is possible to manage class properties through class methods without instantiation, just for encapsulation.

Static methods: When we have a lot of messy and unrelated functions, we need to wrap the functions in a class and not modify the function’s code (parameters), just to wrap the functions in a class for easy management. Such as:

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: Tooldemo2.py @time: 2019/10/23 15:11:13@author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


class Tool(object) :
    Define a toolkit to manage these tools, just for encapsulation without affecting these functions, for ease of administration.
    @staticmethod
    def hammer() :  # a hammer
        pass

    @staticmethod
    def ax() :  # the axe
        pass

    @staticmethod
    def wrench() :  # wrench
        pass


When we need to use these tools, we can call them directly from the class object
No additional parameters are passed, such as the self-instance itself, or the CLS class itself, just for encapsulation
Tool.hammer()
Tool.ax()
Copy the code

Attribute methodproperty

The literal meaning is to make a method a special property, that is, a special property that can be used like the instance property used, corresponding to a method. Such as:

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: testdemo. py @time: 2019/10/23 15:13:21 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


class Test(object) :
    def foo(self) :
        print("in the fo")

    Define the property attribute
    @property
    def bar(self) :
        # print("in the bar")
        return "in the bar"


tt = Test()
tt.foo()  Call the normal instance method -- in the fo
ret = tt.bar  # call the same as a class attribute and return a value -- in the bar
print(ret)
Copy the code

Add an @Property decorator to the instance method, with one and only self argument;

When called, as with class attributes, there are no parentheses

# for jingdong mall is shown in the list page of mainframe computers, each request can't be display all the content in the database to the page, but by the paging function, according to the local request data in the database, so it shows that specify access to articles from the first m to n all the data of this page features include:

Calculate m and N based on the current page and the total number of data items requested by the user
Request data from database according to m and n


class Pager:
    def __init__(self, current_page) :
        # number of pages currently requested by the user (page 1, page 2...)
        self.current_page = current_page
        Display 10 data items per page by default
        self.per_items = 10

    @property
    def start(self) :
        val = (self.current_page - 1) * self.per_items
        return val

    @property
    def end(self) :
        val = self.current_page * self.per_items
        return val


# call
p = Pager(1)
p.start  # is the starting value, which is: m
p.end  # is the end value, which is: n
Copy the code

Add, delete, modify, delete, add, delete, add, delete, add, delete, modify, delete, add, delete, modify, delete, add, delete, delete, delete, add, delete, delete


propertyAdd, delete, modify and check attributes (two ways) :

Two ways:

  1. Has three@propertyA decorator;
  2. Class attribute. The value isProperty objectThe class attribute

Three @property decorators

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: gooddemo. py @time: 2019/10/23 15:17:57 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib

Copy (copy, copy, copy, copy)

class Goods(object) :
    def __init__(self) :
        # the original price
        self.original_price = 100
        # discount
        self.discount = 0.8

    @property
    def price(self) :
        # Actual price = original price * discount
        new_price = self.original_price * self.discount
        return new_price

    @price.setter  # func_name.setter
    def price(self, value) :
        self.original_price = value

    @price.deleter  # func_name.deleter
    def price(self, value) :
        del self.original_price


obj = Goods()
obj.price  # Get commodity prices
obj.price = 200  # Modify the original price of goods
del obj.price  # Delete the original price of the product

It is a bit like magic. When an operation is performed, the decorator is automatically triggered to run
# @property -- When the price property is obtained, the @property modified method is automatically executed and the return value of the method is obtained, for example, obj.func
# @func. Setter -- When set to modify the price property, the @func. Setter decorates the func method automatically and assigns the value to the method's parameters, e.g. Obj. func = 200
# @func. Deleter -- The @func. Deleter modified func method is automatically executed when the price property is deleted
Copy the code

Class attribute. The value isProperty objectThe class attribute

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: foodemo. py @time: 2019/10/23 15:20:30 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


class Foo(object) :
    def get_bar(self) :
        num = 100
        return num

    def set_bar(self, value) :
        """ Must have two parameters """
        num = value
        return num

    def del_bar(self) :
        num = 100
        del num
        return "deleted this attribute"

    Get, modify, delete, and describe
    BAR = property(get_bar, set_bar, del_bar, "description...")


obj = Foo()

obj.BAR  Automatically call the method defined in the first argument: get_bar
obj.BAR = 200  Automatically call the set_bar method defined in the second argument and pass 200 as the argument
del obj.BAR  Automatically call the method defined in the third argument: the del_bar method
desc = Foo.BAR.__doc__  The value set in the fourth parameter: description...
print(desc)
print(obj.BAR)
Copy the code

The use of the property attribute is common and has obvious advantages:

To provide users with a simple property, rather than a complex function (regardless of what the parameters of the function are, what the return value of the function is), just call the property to get the return value of the function. In essence, it is also the embodiment of encapsulation, that is, encapsulation of the underlying complex implementation mode, to provide users with a simple, use attribute interface. Here are the codes for large companies:

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: messageDemo.py Tencent instant messaging module - refer to @time: 2019/10/23 15:28:04 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib

# coding: utf-8

import random
import time


class Message(object) :
    def __init__(self, msgarr=[], toacc=' ') :
        self.msgbody = msgarr  This is a list or an empty list of MsgDict object instances
        self.toacc = toacc  # toacc for strings (single) or lists (batch)
        self.msgrandom = random.randint(1.1000000000)
        self.msgrequest = {
            'To_Account': toacc,  # Message recipient account
            'MsgRandom': self.msgrandom,  # Random number of messages generated by a random function
            'MsgBody': [t.msg for t in msgarr]
        }

    def del_option(self, option) :
        if option in (set(self.msgrequest) -
                      set(['To_Account'.'MsgRandom'.'MsgBody'])):
            self.__dict__.pop(option)
            self.msgrequest.pop(option)

    def append_msg(self, msg) :
        self.msgbody.append(msg)
        self.msgrequest['MsgBody'].append(msg.msg)

    def insert_msg(self, index, msg) :
        self.msgbody.insert(index, msg)
        self.msgrequest['MsgBody'].insert(msg.msg)

    def del_msg(self, index) :
        if index in range(len(self.msgbody)):
            del self.msgbody[index]
            del self.msgrequest['MsgBody'][index]

    def set_from(self, fromacc) :
        Specifies the sender of the message. Default is the server
        self.fromacc = fromacc
        self.msgrequest['From_Account'] = fromacc

    def set_to(self, toacc) :
        List(batch sent); String(single sent)
        self.toacc = toacc
        self.msgrequest['To_Account'] = toacc

    def refresh_random(self) :
        self.msgrandom = random.randint(1.1000000000)
        self.msgrequest['MsgRandom'] = self.msgrandom,  # Random number of messages generated by a random function

    def set_sync(self, sync) :
        1. Synchronize messages to From_Account online terminal and roaming
        # 2, messages are not synchronized to From_Account
        # If this parameter is not specified, the message will be synchronized by default
        Can only be called in single message
        self.sync = sync
        self.msgrequest['SyncOtherMachine'] = sync

    def set_timestamp(self) :
        # Set message timestamp, Unix time, can only be called in single message
        self.timestamp = int(time.time())
        self.msgrequest['MsgTimeStamp'] = self.timestamp

    def set_offlinepush(self, pushflag=0, desc=' ', ext=' ', sound=' ') :
        # this only works with APNa, not android vendors
        self.msgrequest['OfflinePushInfo'] = {
            'PushFlag': pushflag,
            'Desc': desc,
            'Ext': ext,
            'Sound': sound
        }


class MsgDict(object) :
    def __init__(self, msgtype=' ', msgcontent={}) :
        self.msgtype = msgtype
        self.msgcontent = msgcontent

    @property
    def msg(self) :
        return {'MsgType': self.msgtype, 'MsgContent': self.msgcontent}

    def set_content(self, content) :
        self.msgcontent = content


class TextMsg(MsgDict) :
    def __init__(self, text=' ', msgtype='TIMTextElem') :
        self.text = text
        content = {'Text': text}
        super(TextMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_text(self, text) :
        self.text = text
        self.msgcontent['Text'] = text


class LocationMsg(MsgDict) :
    def __init__(self,
                 desc=' ',
                 latitude=0,
                 longitude=0,
                 msgtype='TIMLocationElem') :
        self.desc = desc
        self.latitude = latitude
        self.longitude = longitude
        content = {
            'Desc': desc,  # Geolocation description, String
            'Latitude': latitude,  # latitude, Number
            'Longitude': longitude  # longitude, Number
        }
        super(LocationMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_desc(self, desc) :
        self.desc = desc
        self.msgcontent['Desc'] = desc

    def set_location(self, latitude, longitude) :
        self.latitude = latitude
        self.longitude = longitude
        self.msgcontent['Latitude'] = latitude
        self.msgcontent['Longitude'] = longitude

    def set_latitude(self, latitude) :
        self.latitude = latitude
        self.msgcontent['Latitude'] = latitude

    def set_longitude(self, longitude) :
        self.longitude = longitude
        self.msgcontent['Longitude'] = longitude


class FaceMsg(MsgDict) :
    def __init__(self, index=1, data=' ', msgtype='TIMFaceElem') :
        self.index = index
        self.data = data
        content = {
            'Index': index,  # emoticon index, user defined, Number
            'Data': data  # Extra data, String
        }
        super(TextMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_index(self, index) :
        self.index = index
        self.msgcontent['Index'] = index

    def set_data(self, data) :
        self.data = data
        self.msgcontent['Data'] = data


class CustomMsg(MsgDict) :
    def __init__(self,
                 data=' ',
                 desc=' ',
                 ext=' ',
                 sound=' ',
                 msgtype='TIMCustomElem') :
        self.data = data
        self.desc = desc
        self.ext = ext
        self.sound = sound
        content = {
            'Data':
            data,  # Customize message data. This field is not delivered as a field in the payload of APNS. Therefore, the Data field (String) cannot be obtained from the payload
            'Desc': desc,  # Custom message description: when the receiver is on the background of iPhone, do the text display of ios offline Push
            'Ext':
            ext,  This field is delivered as the ext key in the APNS Payloads when the receiver is ios and the application is in the background. The protocol format of the EXT is determined by the business side and APNS only does transparent transmission
            'Sound': sound  # Custom APNS push ringtone
        }
        super(CustomMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_data(self, data) :
        self.data = data
        self.msgcontent['Data'] = data

    def set_desc(self, desc) :
        self.desc = desc
        self.msgcontent['Desc'] = desc

    def set_ext(self, ext) :
        self.ext = ext
        self.msgcontent['Ext'] = ext

    def set_sound(self, sound) :
        self.sound = sound
        self.msgcontent['Sound'] = sound


class SoundMsg(MsgDict) :
    def __init__(self, uuid=' ', size=0, second=0, msgtype='TIMSoundElem') :
        self.uuid = uuid
        self.size = size
        self.second = second
        content = {
            'UUID': uuid,  # voice serial number, background used to index the voice key value, String
            'Size': size,  # Voice data size, Number
            'Second': second  Voice duration in seconds Number
        }
        super(SoundMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_uuid(self, uuid) :
        self.uuid = uuid
        self.msgcontent['UUID'] = uuid

    def set_size(self, size) :
        self.size = size
        self.msgcontent['Size'] = size

    def set_second(self, second) :
        self.second = second
        self.msgcontent['Second'] = second


class ImageMsg(MsgDict) :
    def __init__(self,
                 uuid=' ',
                 imgformat=0,
                 imginfo=[],
                 msgtype='TIMImageElem') :
        self.uuid = uuid
        self.imgformat = imgformat
        self.imginfo = imginfo
        content = {
            'UUID': uuid,  # image serial number, background used to index speech key value, String
            'ImageFormat':
            imgformat,  BMP=1, JPG=2, GIF=3, other =0, Number
            'ImageInfoArray':
            [t.info for t in imginfo]  # Original image, thumbnail or large image download information, Array
        }
        super(ImageMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_uuid(self, uuid) :
        self.uuid = uuid
        self.msgcontent['UUID'] = uuid

    def set_format(self, imgformat) :
        self.imgformat = imgformat
        self.msgcontent['ImageFormat'] = imgformat

    def append_info(self, info) :
        # info is an instance of the ImageInfo object
        self.imginfo.append(info)
        self.msgcontnet['ImageInfoArray'].append(info.info)

    def insert_info(self, index, info) :
        self.imginfo.insert(index, info)
        self.msgcontent['ImageInfoArray'].insert(index, info.info)

    def del_info(self, index) :
        del self.imginfo[index]
        del self.msgcontent['ImageInfoArray'][index]


class FileMsg(MsgDict) :
    def __init__(self, uuid=' ', size=0, name=' ', msgtype='TIMFileElem') :
        self.uuid = uuid
        self.size = size
        self.name = name
        content = {
            'UUID': uuid,  # file serial number, background used to index speech key value, String
            'FileSize': size,  # file data size, Number
            'FileName': name  File name/path, String
        }
        super(FileMsg, self).__init__(msgtype=msgtype, msgcontent=content)

    def set_uuid(self, uuid) :
        self.uuid = uuid
        self.msgcontent['UUID'] = UUID

    def set_size(self, size) :
        self.size = size
        self.msgcontent['FileSize'] = size

    def set_name(self, name) :
        self.name = name
        self.msgcontent['FileName'] = name


class ImageInfo(object) :
    def __init__(self, itype=1, size=0, width=0, height=0, url=' ') :
        # Image type, 1- original, 2- large, 3- thumbnail, 0- other
        self.itype = itype
        # image data size,Number
        self.size = size
        # image width,Number
        self.width = width
        # image height, Number
        self.height = height
        # image download address,String
        self.url = url

    @property
    def info(self) :
        return {
            'Type': self.itype,
            'Size': self.size,
            'Width': self.width,
            'Height': self.height,
            'URL': self.url
        }

    def set_type(self, itype) :
        self.itype = itype

    def set_size(self, size) :
        self.size = size

    def set_width(self, width) :
        self.width = width

    def set_height(self, height) :
        self.height = height

    def set_url(self, url) :
        self.url = url
Copy the code

Go and try it!


🎉 finally

  • For more references, see here:Chen Yongjia’s blog

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!