面向对象 - 绑定方法与非绑定方法:
定义:
在类内部定义的函数,分为两大类:
1.绑定方法:绑定给谁,就应该由谁来调用,谁来调用 就会把调用者当作第一个参数自动传入
绑定到对象的方法:在类内部定义的,没有被任何装饰器修饰的
对于类来说 它就是个 普通函数 <function Foo.tell at 0x000001FD0D800B70>
对于对象来说 它就是个 绑定方法 <bound method Foo.tell of <__main__.Foo object at 0x000001FD0D832710>>
绑定到类的方法:在类内部定义的,被装饰器@classmethod 修饰的方法
对于类和对象来说 它就是个 绑定方法 <bound method Foo.func1 of <class '__main__.Foo'>>
2.非绑定方法:
非绑定方法:不与类或对象绑定 在类内部定义的,被装饰器@staticmethod 修饰的方法
对于类和对象来说 它就是个 普通函数 < function Foo.fun2 at 0x00000157332C0C80>
应用:
1.绑定给对象 就应该由对象来调用 自动将对象本身当作第一个参数 传入
def tell_info(self):
2.绑定给类 就应该由类来调用 自动将类本身当作第一个参数 传入
@classmethod def from_conf(cls) # 读配置文件里的内容 一种实例化的方式
3.非绑定方法 不与类或者对象绑定 谁都可以调用 没有自动传值一说
@staticmethod def create_id(): # 创建随机的 id
![]()
1 class Foo:
2 all_type='hello' # 公用的
3 def __init__(self,name): # 绑定到 对象
4 self.name=name
5
6 def tell(self): # 绑定到 对象
7 print('名字是 %s'%self.name)
8
9 @classmethod # 绑定到 类
10 def func1(cls,data):
11 print(cls,data)
12
13 @staticmethod # 非绑定 方法
14 def fun2(x,y):
15 print(x+y)
16
17 f=Foo('alice')
18 # f.tell()
19 # f.func1(2) # 不限制 你使用
20 # Foo.func1(4)
21 # f.fun2(2,3)
22 # Foo.fun2(3,4)
23
24 # print(Foo.tell)
25 # print(f.tell)
26 # print((Foo.func1))
27 # print(f.func1)
28 # print(Foo.fun2)
29 # print(f.fun2)
30 # print(Foo.tell)
31 # print(f.tell)
32 # print(Foo.__init__)
33 # print(f.__init__)
34 # print(Foo.all_type)
35 # print(f.all_type)
36 # Foo.tell(f)
37 # Foo.__init__(f,'aa')
38 # f.tell()
39 # Foo.func1(3)
40
41 import settings
42 import hashlib
43 import time
44 import string
45 import random
46
47 class People:
48 def __init__(self,name,age,sex):
49 self.id=self.create_id()
50 self.name=name
51 self.age=age
52 self.sex=sex
53
54 def tell_info(self): # 绑定到对象 # 根据函数体的逻辑 来想 参数 应该传什么进来
55 print('Name:%s Age:%s Sex:%s'%(self.name,self.age,self.sex))
56
57 @classmethod
58 def from_conf(cls): # 读配置文件里的内容 一种实例化的方式
59 obj=cls(
60 settings.name,
61 settings.age,
62 settings.sex
63 )
64 return obj
65
66 @staticmethod
67 def create_id(): # 创建随机的 id
68 # m=hashlib.md5(str(time.time()).encode('utf-8'))
69 m=hashlib.md5(''.join(random.sample(string.ascii_letters+string.digits+string.punctuation,8)).encode('utf-8'))
70 return m.hexdigest()
71
72 p=People('alice',12,'female')
73 p2=People('alice',12,'female')
74 p3=People('alice',12,'female')
75 # p.tell_info()
76 # print(settings.name,settings.age,settings.sex)
77
78 # People.from_conf().tell_info()
79
80 # print(p.create_id())
81 # print(People.create_id())
82 # print(p.id)
83 # print(p2.id)
84 # print(p3.id)
绑定方法与非绑定方法