Python----面向对象---绑定方法与非绑定方法的应用
1、绑定到对象的方法的应用
1 class People: 2 def __init__(self, name, age, sex): 3 self.name = name 4 self.age = age 5 self.sex = sex 6 7 def tell_info(self): # 绑定到对象的方法 8 print('Name:%s Age:%s Sex:%s' % (self.name, self.age, self.sex)) 9 10 p = People('egon', 18, 'male') 11 p.tell_info() # tell_info(p) 12 13 结果为: 14 15 Name:egon Age:18 Sex:male
绑定给对象,就应该由对象来调用,自动将对象本身当做第一个参数传入
2、绑定给类,就应该由类来调用,自动将类本身当做第一个参数传入
1 import setting 2 3 class People: 4 def __init__(self, name, age, sex): 5 self.name = name 6 self.age = age 7 self.sex = sex 8 9 def tell_info(self): # 绑定到对象的方法 10 print('Name:%s Age:%s Sex:%s' % (self.name, self.age, self.sex)) 11 12 @classmethod 13 def from_conf(cls): 14 obj = cls( 15 setting.name, 16 setting.age, 17 setting.sex 18 ) 19 return obj 20 21 # p = People('egon', 18, 'male') 22 # p.tell_info() # tell_info(p) 23 p = People.from_conf() 24 p.tell_info() 25 26 结果为: 27 28 Name:xudachen Age:18 Sex:male
3、非绑定方法
1 import setting 2 import hashlib 3 import time 4 5 class People: 6 def __init__(self, name, age, sex): 7 self.id = self.create_id() 8 self.name = name 9 self.age = age 10 self.sex = sex 11 12 def tell_info(self): # 绑定到对象的方法 13 print('Name:%s Age:%s Sex:%s' % (self.name, self.age, self.sex)) 14 15 @classmethod 16 def from_conf(cls): 17 obj = cls( 18 setting.name, 19 setting.age, 20 setting.sex 21 ) 22 return obj 23 24 @staticmethod 25 def create_id(): 26 m = hashlib.md5(str(time.time()).encode('utf-8')) 27 return m.hexdigest() 28 29 # p = People('egon', 18, 'male') 30 # p.tell_info() # tell_info(p) 31 # p = People.from_conf() 32 # p.tell_info() 33 34 p1 = People('xudachen1', 18, 'male') 35 p2 = People('xudachen2', 28, 'male') 36 p3 = People('xudachen3', 38, 'male') 37 38 print(p1.id) 39 print(p2.id) 40 print(p3.id) 41 42 结果为: 43 44 1dadcd98fe26e278ce864c2f0cf2e753 45 bc09cd38527ef257fa3158d4e342ea1b 46 bc09cd38527ef257fa3158d4e342ea1b
非绑定方法,不与类或者对象绑定,谁都可以调用,没有自动传值一说