静态方法(staticmethod)和类方法(classmethod)

类方法:有个默认参数cls,并且可以直接用类名去调用,可以与类属性交互(也就是可以使用类属性)

静态方法:让类里的方法直接被类调用,就像正常调用函数一样

类方法和静态方法的相同点:都可以直接被类调用,不需要实例化

类方法和静态方法的不同点:

  类方法必须有一个cls参数表示这个类,可以使用类属性

  静态方法不需要参数

绑定方法:分为普通方法和类方法

     普通方法:默认有一个self对象传进来,并且只能被对象调用-------绑定到对象

      类方法:默认有一个cls对象传进来,并且可以被类和对象(不推荐)调用-----绑定到类

非绑定方法:静态方法:没有设置默认参数,并且可以被类和对象(不推荐)调用-----非绑定

#!/usr/bin/env python
# -*- coding:utf-8 -*-
with open('student','w',encoding='utf-8') as f:
    a = 'abcd,4567'''
    f.write(a)
class Student:
    f = open('student', encoding='utf-8')
    def __init__(self):
        pass
    @classmethod #类方法 :有个默认参数cls,并且可以直接使用类名去
                 #调用,还可以与类属性交互(也就是可以使用类属性)
    def show_student_info_class(cls):
        # f = open('student', encoding='utf-8')
        for line in cls.f:
            name,sex = line.strip().split(',')
            print(name,sex)
    @staticmethod  #静态方法:可以直接使用类名去调用,就像正常的函数调用一样
    def show_student_info_static(): #不用传self
        f = open('student',encoding='utf-8')
        for line in f:
            name,sex = line.strip().split(',')
            print(name,sex)
# egon = Student()
# egon.show_student_info_static()  #也可以这样调,但是还是推荐用类名去调
# egon.show_student_info_class()

Student.show_student_info_class()#类名.方法名()
print('*******************')
Student.show_student_info_static()#类名.方法名()

# staticmethod和classmethod

猜你喜欢

转载自www.cnblogs.com/zhaojingyu/p/9057343.html