|
| 1 | +>所以,自己以为站得稳的,须要谨慎,免得跌倒。你们所遇见的试探,无非是人所能受的。神是信实的,必不叫你们受试探过于所能受的。在受试探的时候,总要给你们开一条出路,叫你们能忍受得住。(1 CORINTHIANS 10:12-13) |
| 2 | +
|
| 3 | +#类(5) |
| 4 | + |
| 5 | +在前面几节讨论类的时候,经常要将类实例化,然后通过实例来调用类的方法(函数)。在此,把前面经常做的这类事情概括一下: |
| 6 | + |
| 7 | +- 方法是类内部定义函数,只不过这个函数的第一个参数是self。(可以认为方法是类属性,但不是实例属性) |
| 8 | +- 必须将类实例化之后,才能通过实例调用该类的方法。调用的时候在方法后面要跟括号(括号中默认有self参数,但是不写出来。) |
| 9 | + |
| 10 | +通过实例调用方法(在前面曾用了一个不严谨的词语:实例方法),我们称这个方法**绑定**在实例上。 |
| 11 | + |
| 12 | +##调用绑定方法 |
| 13 | + |
| 14 | +前面一直在这样做。比如: |
| 15 | + |
| 16 | + class Person(object): |
| 17 | + def foo(self): |
| 18 | + pass |
| 19 | + |
| 20 | +如果要调用Person.foo()方法,必须: |
| 21 | + |
| 22 | + pp = Person() #实例化 |
| 23 | + pp.foo() |
| 24 | + |
| 25 | +这样就实现了方法和实例的绑定,于是通过`pp.foo()`即可调用该方法。 |
| 26 | + |
| 27 | +##调用非绑定方法 |
| 28 | + |
| 29 | +在[《类(4)](./209.md)中,介绍了一个函数super。为了描述方便,把代码复制过来: |
| 30 | + |
| 31 | + #!/usr/bin/env python |
| 32 | + # coding=utf-8 |
| 33 | + |
| 34 | + __metaclass__ = type |
| 35 | + |
| 36 | + class Person: |
| 37 | + def __init__(self): |
| 38 | + self.height = 160 |
| 39 | + |
| 40 | + def about(self, name): |
| 41 | + print "{} is about {}".format(name, self.height) |
| 42 | + |
| 43 | + class Girl(Person): |
| 44 | + def __init__(self): |
| 45 | + super(Girl, self).__init__() |
| 46 | + self.breast = 90 |
| 47 | + |
| 48 | + def about(self, name): |
| 49 | + print "{} is a hot girl, she is about {}, and her breast is {}".format(name, self.height, self.breast) |
| 50 | + super(Girl, self).about(name) |
| 51 | + |
| 52 | + if __name__ == "__main__": |
| 53 | + cang = Girl() |
| 54 | + cang.about("canglaoshi") |
| 55 | + |
| 56 | +在子类Girl中,因为重写了父类的`__init__`方法,如果要调用父类该方法,在上节中不得不使用`super(Girl, self).__init__()`调用父类中因为子类方法重写而被遮蔽的同名方法。 |
| 57 | + |
| 58 | +其实,在子类中,父类的方法就是**非绑定方法**,因为在子类中,没有建立父类的实例,却要是用父类的方法。对于这种非绑定方法的调用,还有一种方式。不过这种方式现在已经较少是用了,因为有了super函数。为了方便读者看其它有关代码,还是要简要说明。 |
| 59 | + |
| 60 | +例如在上面代码中,在类Girl中想调用父类Person的初始化函数,则需要在子类中,写上这么一行: |
| 61 | + |
| 62 | + Person.__init__(self) |
| 63 | + |
| 64 | +这不是通过实例调用的,而是通过类Person实现了对`__init__(self)`的调用。这就是调用非绑定方法的用途。但是,这种方法已经被super函数取代,所以,如果读者在编程中遇到类似情况,推荐使用super函数。 |
| 65 | + |
| 66 | +##静态方法和类方法 |
| 67 | + |
| 68 | +已知,类的方法第一个参数必须是self,并且如果要调用类的方法,必须将通过类的实例,即方法绑定实例后才能由实例调用。如果不绑定,一般在继承关系的类之间,可以用super函数等方法调用。 |
| 69 | + |
| 70 | +这里再介绍一种方法,这种方法的调用方式跟上述的都不同,这就是:静态方法和类方法。看代码: |
| 71 | + |
| 72 | + #!/usr/bin/env python |
| 73 | + # coding=utf-8 |
| 74 | + |
| 75 | + __metaclass__ = type |
| 76 | + |
| 77 | + class StaticMethod: |
| 78 | + @staticmethod |
| 79 | + def foo(): |
| 80 | + print "This is static method foo()." |
| 81 | + |
| 82 | + class ClassMethod: |
| 83 | + @classmethod |
| 84 | + def bar(cls): |
| 85 | + print "This is class method bar()." |
| 86 | + print "bar() is part of class:", cls.__name__ |
| 87 | + |
| 88 | + if __name__ == "__main__": |
| 89 | + static_foo = StaticMethod() #实例化 |
| 90 | + static_foo.foo() #实例调用静态方法 |
| 91 | + StaticMethod.foo() #通过类来调用静态方法 |
| 92 | + print "********" |
| 93 | + class_bar = ClassMethod() |
| 94 | + class_bar.bar() |
| 95 | + ClassMethod.bar() |
| 96 | + |
| 97 | +对于这部分代码,有一处非常特别,那就是包含了“@”符号。在python中: |
| 98 | + |
| 99 | +- `@staticmethod`表示下面的方法是静态方法 |
| 100 | +- `@classmethod`表示下面的方法是类方法 |
| 101 | + |
| 102 | +一个一个来看。 |
| 103 | + |
| 104 | +先看静态方法,虽然名为静态方法,但也是方法,所以,依然用def语句来定义。需要注意的是文件名后面的括号内,没有self,这和前面定义的类中的方法是不同的,也正是因着这个不同,才给它另外取了一个名字叫做静态方法,否则不就“泯然众人矣”。如果没有self,那么也就无法访问实例变量、类和实例的属性了,因为它们都是借助self来传递数据的。 |
| 105 | + |
| 106 | +在看类方法,同样也具有一般方法的特点,区别也在参数上。类方法的参数也没有self,但是必须有cls这个参数。在类方法中,能够方法类属性,但是不能访问实例属性(读者可以自行设计代码检验之)。 |
| 107 | + |
| 108 | +简要明确两种方法。下面看调用方法。两种方法都可以通过实例调用,即绑定实例。也可以通过类来调用,即`StaticMethod.foo()`这样的形式,这也是区别一般方法的地方,一般方法必须用通过绑定实例调用。 |
| 109 | + |
| 110 | +上述代码运行结果: |
| 111 | + |
| 112 | + $ python 21001.py |
| 113 | + This is static method foo(). |
| 114 | + This is static method foo(). |
| 115 | + ******** |
| 116 | + This is class method bar(). |
| 117 | + bar() is part of class: ClassMethod |
| 118 | + This is class method bar(). |
| 119 | + bar() is part of class: ClassMethod |
| 120 | + |
| 121 | +这是关于静态方法和类方法的简要介绍。 |
| 122 | + |
| 123 | +正当我思考如何讲解的更深入一点的时候,我想起了以往看过的一篇文章,觉得人家讲的非常到位。所以,不敢吝啬,更不敢班门弄斧,所以干醋把那篇文章恭恭敬敬的抄录于此。同时,读者从下面的文章中,也能对前面的知识复习一下。文章标题是:python中的staticmethod和classmethod的差异。原载:www.pythoncentral.io/difference-between-staticmethod-and-classmethod-in-python/。此地址需要你准备梯子才能浏览。后经国人翻译,地址是:http://www.wklken.me/posts/2013/12/22/difference-between-staticmethod-and-classmethod-in-python.html |
| 124 | + |
| 125 | +以下是翻译文章: |
| 126 | + |
| 127 | +###Class vs static methods in Python |
| 128 | + |
| 129 | +这篇文章试图解释:什么事staticmethod/classmethod,并且这两者之间的差异. |
| 130 | + |
| 131 | +staticmethod和classmethod均被作为装饰器,用作定义一个函数为"staticmethod"还是"classmethod" |
| 132 | + |
| 133 | +如果想要了解Python装饰器的基础,可以看[这篇文章](http://www.pythoncentral.io/python-decorators-overview/) |
| 134 | + |
| 135 | +###Simple, static and class methods |
| 136 | + |
| 137 | +类中最常用到的方法是 实例方法(instance methods), 即,实例对象作为第一个参数传递给函数 |
| 138 | + |
| 139 | +例如,下面是一个基本的实例方法 |
| 140 | + |
| 141 | + class Kls(object): |
| 142 | + def __init__(self, data): |
| 143 | + self.data = data |
| 144 | + |
| 145 | + def printd(self): |
| 146 | + print(self.data) |
| 147 | + |
| 148 | + ik1 = Kls('arun') |
| 149 | + ik2 = Kls('seema') |
| 150 | + |
| 151 | + ik1.printd() |
| 152 | + ik2.printd() |
| 153 | + |
| 154 | +得到的输出: |
| 155 | + |
| 156 | + arun |
| 157 | + seema |
| 158 | + |
| 159 | +调用关系图: |
| 160 | + |
| 161 | + |
| 162 | + |
| 163 | +查看代码和图解: |
| 164 | + |
| 165 | +>1/2 参数传递给函数 |
| 166 | +>3 self参数指向实例本身 |
| 167 | +>4 我们不需要显式提供实例,解释器本身会处理 |
| 168 | +
|
| 169 | +假如我们想仅实现类之间交互而不是通过实例?我们可以在类之外建立一个简单的函数来实现这个功能,但是将会使代码扩散到类之外,这个可能对未来代码维护带来问题。 |
| 170 | + |
| 171 | +例如: |
| 172 | + |
| 173 | + def get_no_of_instances(cls_obj): |
| 174 | + return cls_obj.no_inst |
| 175 | + |
| 176 | + class Kls(object): |
| 177 | + no_inst = 0 |
| 178 | + |
| 179 | + def __init__(self): |
| 180 | + Kls.no_inst = Kls.no_inst + 1 |
| 181 | + |
| 182 | + ik1 = Kls() |
| 183 | + ik2 = Kls() |
| 184 | + |
| 185 | + print(get_no_of_instances(Kls)) |
| 186 | + |
| 187 | +结果: |
| 188 | + |
| 189 | + 2 |
| 190 | + |
| 191 | +###The Python @classmethod |
| 192 | + |
| 193 | +现在我们要做的是在类里创建一个函数,这个函数参数是类对象而不是实例对象. |
| 194 | + |
| 195 | +在上面那个实现中,如果要实现不获取实例,需要修改如下: |
| 196 | + |
| 197 | + def iget_no_of_instance(ins_obj): |
| 198 | + return ins_obj.__class__.no_inst |
| 199 | + |
| 200 | + class Kls(object): |
| 201 | + no_inst = 0 |
| 202 | + |
| 203 | + def __init__(self): |
| 204 | + Kls.no_inst = Kls.no_inst + 1 |
| 205 | + |
| 206 | + ik1 = Kls() |
| 207 | + ik2 = Kls() |
| 208 | + print iget_no_of_instance(ik1) |
| 209 | + |
| 210 | +结果 |
| 211 | + |
| 212 | + 2 |
| 213 | + |
| 214 | +可以使用Python2.2引入的新特性,使用@classmethod在类代码中创建一个函数 |
| 215 | + |
| 216 | + class Kls(object): |
| 217 | + no_inst = 0 |
| 218 | + |
| 219 | + def __init__(self): |
| 220 | + Kls.no_inst = Kls.no_inst + 1 |
| 221 | + |
| 222 | + @classmethod |
| 223 | + def get_no_of_instance(cls_obj): |
| 224 | + return cls_obj.no_inst |
| 225 | + |
| 226 | + ik1 = Kls() |
| 227 | + ik2 = Kls() |
| 228 | + |
| 229 | + print ik1.get_no_of_instance() |
| 230 | + print Kls.get_no_of_instance() |
| 231 | + |
| 232 | +We get the following output: |
| 233 | + |
| 234 | + 2 |
| 235 | + 2 |
| 236 | + |
| 237 | +###The Python @staticmethod |
| 238 | + |
| 239 | +通常,有很多情况下一些函数与类相关,但不需要任何类或实例变量就可以实现一些功能. |
| 240 | + |
| 241 | +比如设置环境变量,修改另一个类的属性等等.这种情况下,我们也可以使用一个函数,一样会将代码扩散到类之外(难以维护) |
| 242 | + |
| 243 | +下面是一个例子: |
| 244 | + |
| 245 | + IND = 'ON' |
| 246 | + |
| 247 | + def checkind(): |
| 248 | + return (IND == 'ON') |
| 249 | + |
| 250 | + class Kls(object): |
| 251 | + def __init__(self,data): |
| 252 | + self.data = data |
| 253 | + |
| 254 | + def do_reset(self): |
| 255 | + if checkind(): |
| 256 | + print('Reset done for:', self.data) |
| 257 | + |
| 258 | + def set_db(self): |
| 259 | + if checkind(): |
| 260 | + self.db = 'new db connection' |
| 261 | + print('DB connection made for:',self.data) |
| 262 | + |
| 263 | + ik1 = Kls(12) |
| 264 | + ik1.do_reset() |
| 265 | + ik1.set_db() |
| 266 | + |
| 267 | +结果: |
| 268 | + |
| 269 | + Reset done for: 12 |
| 270 | + DB connection made for: 12 |
| 271 | + |
| 272 | +现在我们使用@staticmethod, 我们可以将所有代码放到类中 |
| 273 | + |
| 274 | + IND = 'ON' |
| 275 | + |
| 276 | + class Kls(object): |
| 277 | + def __init__(self, data): |
| 278 | + self.data = data |
| 279 | + |
| 280 | + @staticmethod |
| 281 | + def checkind(): |
| 282 | + return (IND == 'ON') |
| 283 | + |
| 284 | + def do_reset(self): |
| 285 | + if self.checkind(): |
| 286 | + print('Reset done for:', self.data) |
| 287 | + |
| 288 | + def set_db(self): |
| 289 | + if self.checkind(): |
| 290 | + self.db = 'New db connection' |
| 291 | + print('DB connection made for: ', self.data) |
| 292 | + |
| 293 | + ik1 = Kls(12) |
| 294 | + ik1.do_reset() |
| 295 | + ik1.set_db() |
| 296 | + |
| 297 | +得到的结果: |
| 298 | + |
| 299 | + Reset done for: 12 |
| 300 | + DB connection made for: 12 |
| 301 | + |
| 302 | +###How @staticmethod and @classmethod are different |
| 303 | + |
| 304 | + class Kls(object): |
| 305 | + def __init__(self, data): |
| 306 | + self.data = data |
| 307 | + |
| 308 | + def printd(self): |
| 309 | + print(self.data) |
| 310 | + |
| 311 | + @staticmethod |
| 312 | + def smethod(*arg): |
| 313 | + print('Static:', arg) |
| 314 | + |
| 315 | + @classmethod |
| 316 | + def cmethod(*arg): |
| 317 | + print('Class:', arg) |
| 318 | + |
| 319 | +调用 |
| 320 | + |
| 321 | + >>> ik = Kls(23) |
| 322 | + >>> ik.printd() |
| 323 | + 23 |
| 324 | + >>> ik.smethod() |
| 325 | + Static: () |
| 326 | + >>> ik.cmethod() |
| 327 | + Class: (<class '__main__.Kls'>,) |
| 328 | + >>> Kls.printd() |
| 329 | + TypeError: unbound method printd() must be called with Kls instance as first argument (got nothing instead) |
| 330 | + >>> Kls.smethod() |
| 331 | + Static: () |
| 332 | + >>> Kls.cmethod() |
| 333 | + Class: (<class '__main__.Kls'>,) |
| 334 | + |
| 335 | +图解 |
| 336 | + |
| 337 | + |
| 338 | + |
| 339 | +##文档字符串 |
| 340 | + |
| 341 | +在写程序的时候,必须要写必要的文字说明,没别的原因,除非你的代码写的非常容易理解,特别是各种变量、函数和类等的命名任何人都能够很容易理解,否则,文字说明是不可缺少的。 |
| 342 | + |
| 343 | +在函数、类或者文件开头的部分写文档字符串说明,一般采用三重引号。这样写的最大好处是能够用help()函数看。 |
| 344 | + |
| 345 | + """This is python lesson""" |
| 346 | + |
| 347 | + def start_func(arg): |
| 348 | + """This is a function.""" |
| 349 | + pass |
| 350 | + |
| 351 | + class MyClass: |
| 352 | + """Thi is my class.""" |
| 353 | + def my_method(self,arg): |
| 354 | + """This is my method.""" |
| 355 | + pass |
| 356 | + |
| 357 | +这样的文档是必须的。 |
| 358 | + |
| 359 | +当然,在编程中,有不少地方要用“#”符号来做注释。一般用这个来注释局部。 |
| 360 | + |
| 361 | +------ |
| 362 | + |
| 363 | +[总目录](./index.md) | [上节:类(4)](./209.md) | [下节:类(6)](./211.md) |
| 364 | + |
| 365 | +如果你认为有必要打赏我,请通过支付宝: **[email protected]**,不胜感激。 |
0 commit comments