• 面向对象编程(类的绑定方法与非绑定方法)


    链接 https://www.cnblogs.com/vipchenwei/p/7126772.html

    1.对象绑定方法

    1.凡是类中的方法和函数,都是绑定给对象使用的;

    2.绑定方法都有自动传值的功能。传递进去的值,就是对象本身。

    3.如果类想调用绑定方法,就必须遵循函数的参数规则,有几个参数,就必须传递几个参数。

    2.类的绑定方法

    类中方法默认都是绑定给对象使用,当对象调用绑定方法时,会自动将对象作为第一个参数传递进去;而类来调用,则必须遵循函数参数一一对应的规则,有几个参数,就必须传递几个参数。如果一个方法是用了@classmethod装饰器,那么這个方法绑定到类身上,不管是对象来调用还是类调用,都会将类作为第一个参数传递进去。

    3.非绑定方法 @staticmethod

    python给我们提供了@staticmethod,可以解除绑定关系,将一个类中的方法,变为一个普通函数。

    下面,我们来看看代码示例:

    # -*- coding: utf-8 -*-
    import hashlib
    import time
    class MySQL:
        def __init__(self,host,port):
            self.id=self.create_id()
            self.host=host
            self.port=port
        @staticmethod
        def create_id(): #就是一个普通工具
            m=hashlib.md5(str(time.clock()).encode('utf-8'))
            return m.hexdigest()
    
    
    print(MySQL.create_id) #<function MySQL.create_id at 0x0000000001E6B9D8> #查看结果为普通函数
    conn=MySQL('127.0.0.1',3306)
    print(conn.create_id) #<fun
    
    #输出
    <function MySQL.create_id at 0x000001D240CD1268>
    <function MySQL.create_id at 0x000001D240CD1268>

    从上面的输出结果,我们可以看出,使用了@staticmethod装饰了一个函数,那么这个函数跟普通函数没有什么区别。既然是普通函数,那么就遵从函数参数传递规则,有几个参数就传递几个参数。

  • 相关阅读:
    final
    Leetcode Single Number
    Leetcode Implement strStr()
    Leetcode Count and Say
    Leetcode Paint Fence
    Leetcode Isomorphic Strings
    Leetcode Min Stack
    Leetcode Valid Sudoku
    Leetcode Two Sum III
    Leetcode Read N Characters Given Read4
  • 原文地址:https://www.cnblogs.com/mjiu/p/8979807.html
Copyright © 2020-2023  润新知