Python/Article/PythonBasis/python8/3.md

58 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 三、类方法 #
## 1、类方法如何调用类属性 ##
通过上面我们已经会定义类了,那么这里讲一下在同一个类里,类方法如何调用类属性的。
直接看个例子吧:
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-08-110451.png)
注意看,在类方法上面多了个 `@classmethod` ,这是干嘛用的呢?
这是用于声明下面的函数是类函数。其实从名字就很好理解了。
class 就是类method 就是方法。
那是不是一定需要注明这个呢?
答案是是的。
如果你没使用,是会报错的。
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-08-110822.png)
如果没有声明是类方法,方法参数中就没有 `cls` , 就没法通过 `cls` 获取到类属性。
因此类方法,想要调用类属性,需要以下步骤:
* 在方法上面,用 `@classmethod` 声明该方法是类方法。只有声明了是类方法,才能使用类属性
* 类方法想要使用类属性,在第一个参数中,需要写上 `cls` , cls 是 class 的缩写,其实意思就是把这个类作为参数,传给自己,这样就可以使用类属性了。
* 类属性的使用方式就是 `cls.变量名`
记住喔,无论是 `@classmethod` 还是 `cls` ,都是不能省去的。
省了都会报错。
## 2、类方法传参 ##
上面我们学习了类方法如何调用类属性,那么类方法如何传参呢?
其实很简单,跟普通的函数一样,直接增加参数就好了。
这个就直接上例子了:
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-08-113458.png)