Logo
Section 1 / 4

Python中的类简介

本章我们将探讨 Python 中的类。

导入

Python中的类简介

本章我们将探讨 Python 中的类。

在 Python 中,一切都是对象。这句话听起来可能很模糊,除非你上过一两门计算机编程课程。它的意思是,Python 中的每一个“东西”都拥有方法和属性。之所以如此,是因为所有事物都是基于类的。类是对象的蓝图。让我们来看一个例子:

1x = "Mike" 2attrs = dir(x) 3print(attrs) 4 5# ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 6# '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 7# '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', 8# '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 9# '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 10# '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 11# 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 12# 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 13# 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 14# 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 15# 'translate', 'upper', 'zfill']

这里我们把一个字符串赋值给了变量 x。它看起来可能没什么特别的,但这个字符串实际上有很多方法。如果你使用 Python 的 dir 函数,就可以得到该字符串所有可调用的方法列表。这里一共有 71 个方法!严格来说,以下划线开头的方法不应直接调用,因此实际可用的方法减少到 38 个,但这依然非常多!这意味着什么?这意味着字符串是基于某个类创建的,而 x 就是这个类的一个实例!

在 Python 中,我们也可以自己定义类。现在就开始学习吧!

函数

创建一个类