5.10 对比 self,cls参数

python类里会出现这三个单词,self和cls都可以用别的单词代替,类的方法有三种,

一是通过def定义的 普通的一般的,需要至少传递一个参数,一般用self,这样的方法必须通过一个类的实例去访问,类似于c++中通过对象去访问;

二是在def前面加上@classmethod,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用;

三是在def前面加上@staticmethod,这种类方法是静态的类方法,类似于c++的静态函数,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式;

class A:
    member = "this is a test."

    def __init__(self):
        pass

    @classmethod
    def Print1(cls):
        print("print 1: ", cls.member)

    def Print2(self):
        print("print 2: ", self.member)

    @classmethod
    def Print3(paraTest):
        print("print 3: ", paraTest.member)

    @staticmethod
    def print4():
        print("hello")


a = A()
A.Print1()  #结果是  print 1:  this is a test.
a.Print1()  #结果是  print 1:  this is a test.
# A.Print2()
a.Print2()  #结果是  print 2:  this is a test.
A.Print3()  #结果是  print 3:  this is a test.
a.Print3()  #结果是  print 3:  this is a test.
A.print4()  #结果是  hello
a.print4() #结果是 hello
 
posted @ 2018-02-26 19:40  Love_always_online  阅读(107)  评论(0编辑  收藏  举报