GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Python-Introduction-Tutorial/Article/PythonBasis/python8/3.md at master · Sogrey/Python-Introduction-Tutorial

Expand file tree

/

3.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
57 lines (24 loc) · 1.61 KB
/

3.md

Copy path

File metadata and controls

57 lines (24 loc) · 1.61 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

三、类方法

1、类方法如何调用类属性

通过上面我们已经会定义类了,那么这里讲一下在同一个类里,类方法如何调用类属性的。

直接看个例子吧:

注意看,在类方法上面多了个 @classmethod ,这是干嘛用的呢?

这是用于声明下面的函数是类函数。其实从名字就很好理解了。

class 就是类,method 就是方法。

那是不是一定需要注明这个呢?

答案是是的。

如果你没使用,是会报错的。

如果没有声明是类方法,方法参数中就没有 cls , 就没法通过 cls 获取到类属性。

因此类方法,想要调用类属性,需要以下步骤:

  • 在方法上面,用 @classmethod 声明该方法是类方法。只有声明了是类方法,才能使用类属性
  • 类方法想要使用类属性,在第一个参数中,需要写上 cls , cls 是 class 的缩写,其实意思就是把这个类作为参数,传给自己,这样就可以使用类属性了。
  • 类属性的使用方式就是 cls.变量名

记住喔,无论是 @classmethod 还是 cls ,都是不能省去的。

省了都会报错。

2、类方法传参

上面我们学习了类方法如何调用类属性,那么类方法如何传参呢?

其实很简单,跟普通的函数一样,直接增加参数就好了。

这个就直接上例子了:

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.