zoukankan      html  css  js  c++  java
  • 三.绑定方法与非绑定方法

    # 类中定义的函数有两大类(3小种)用途,一类是绑定方法,另外一类是非绑定方法
    
    # 1. 绑定方法:
    # 特点:绑定给谁就应该由谁来调用,谁来调用就会将谁当作第一个参数自动传入
    # 1.1 绑定给对象的:类中定义的函数默认就是绑定对象的
    # 1.2 绑定给类的:在类中定义的函数上加一个装饰器classmethod
    
    
    # 2. 非绑定方法
    # 特点: 既不与类绑定也不与对象绑定,意味着对象或者类都可以调用,但无论谁来调用都是一个普通函数,根本没有自动传值一说
    

      

     1 class Foo:
     2     def func1(self):
     3         print('绑定给对象的方法', self)
     4 
     5     @classmethod
     6     def func2(cls):
     7         print('绑定给类的方法', cls)
     8 
     9     @staticmethod
    10     def func3(x, y, z):
    11         print('普通函数')
    12 
    13 
    14 obj = Foo()
    15 obj.func1()  # 绑定给对象的方法 <__main__.Foo object at 0x0000000000B42BE0>
    16 
    17 Foo.func2()  # 绑定给类的方法 <class '__main__.Foo'>
    18 
    19 obj.func3(1, 2, 3)  # 普通函数
    20 Foo.func3(1, 2, 3)  # 普通函数
    21 
    22 # case
    23 import setting
    24 
    25 
    26 class Mysql:
    27     def __init__(self, ip, port):
    28         self.id = self.create_id()
    29         self.ip = ip
    30         self.port = port
    31 
    32     def tell_info(self):
    33         print('%s:%s:%s' % (self.id, self.ip, self.port))
    34 
    35     @classmethod
    36     def from_conf(cls):
    37         return cls(setting.ip, setting.port)
    38 
    39     @staticmethod
    40     def create_id():
    41         import uuid
    42         return uuid.uuid4()
    43 
    44 
    45 obj = Mysql.from_conf()
    46 obj.tell_info()  # 04fd823a-0f04-400b-bf64-6545760d6490:192.168.1.1:3306
  • 相关阅读:
    PHP全部手册
    你必须收藏的GitHub技巧
    PV和并发
    api接口
    LeetCode 14. 最长公共前缀
    LeetCode 1037. 有效的回旋镖
    LeetCode 242. 有效的字母异位词
    LeetCode 151. 翻转字符串里的单词
    LeetCode 22. 括号生成
    LeetCode 面试题05. 替换空格
  • 原文地址:https://www.cnblogs.com/yspass/p/9581743.html
Copyright © 2011-2022 走看看