''' 类中定义的函数: 一、绑定方法 1、绑定类的方法(类方法) 2、绑定对象(类中的普通方法) 二、非绑定方法(静态方法) 不进行绑定,不存在自动传值。 类方法:@classmethod 类方法的第一参数是绑定的类,即调用时(类、对象)会将类传入 class Test: @classmethod def test(cls): #在类方法内部,可以直接使用cls访问类属性和类方法 pass 静态方法:@staticmethod 没有绑定类或对象的方法,不存在自动传参。可自由被调用、传参 class Test: @staticmethod def test(): #调用方式:类名.函数名 pass 类方法、类中普通方法、静态方法: 所以逻辑上,类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。 主要区别在于参数传递上的区别,实例方法悄悄传递的是self引用作为参数,而类方法悄悄传递的是cls引用作为参数。 ''' class Test2: def f1(self): print('f1') @classmethod def f2(cls): print(cls) @staticmethod def f3(): print('f3') t = Test2() t.f1() t.f2() Test2.f2() t.f3() Test2.f3() # ------------------------ import settings class MySql: def __init__(self, ip, port): self.id = self.create_id() self.ip = ip self.port = port def tell_info(self): print(self.id, self.ip, self.port) @classmethod def from_conf(cls): # 用于获取类,免于传参操作 return cls(settings.IP, settings.PORT) @staticmethod def create_id(): import uuid # uuid模块获取唯一加密序列号 return uuid.uuid4() obj = MySql.from_conf() obj.tell_info()
python3-类与对象-类中定义的函数-绑定方法、非绑定方法
猜你喜欢
转载自blog.csdn.net/qq_33961117/article/details/81939454
今日推荐
周排行