【Python基础教程】类的定义和使用

兄弟们,大家好,今天我们分享类的定义和用法。

[En]

Hello, brothers, today we share the definition and use of classes.

在Python中,类表示具有相同属性和方法的对象的集合。在使用类时,需要先定义类,然后再创建类的实例,通过类的实例就可以访问类中的属性和方法了。

1、定义类

在Python中,类的定义使用class关键字来实现,语法如下:

class ClassName:
"""类的帮助信息""" # 类文本字符串
statement # 类体# Python源码、教程获取群 279199867

参数说明

  • ClassName:用于指定类名,一般使用大写字母开头,如果类名中包括个词,第二个单词的首字母也要大写,这种命名方法也称为”驼峰式命名法”,这是惯例。当然,也可以根据自己的习惯命名,但是一般推荐按照惯例来命名。
  • “类的帮助信息”:用于指定类的文档字符串。定义该字符串后,在创建类的对象时,输入类名和左侧的括号”( ” 后,将显示信息。
  • statement:类体,主要由类变量(或类成员)、方法和属性等定义语句组成。如果在定义类时,没有想好类的具体功能,也可以在类体中直接使用Pass语句代替。
class Geese:
"""大雁类"""
pass

2、创建类的实例

一旦定义完成,就不会实际创建实例。这就像是一辆汽车的设计。蓝图可以告诉你汽车是什么样子的,但蓝图本身并不是一辆汽车。你不能开它,它只能用来制造真正的汽车,你可以用它来制造很多汽车。那么,如何创建一个实例呢?

[En]

Once the definition is complete, an instance is not actually created. This is like the design of a car. The blueprint can tell you what the car looks like, but the blueprint itself is not a car. You can’t drive it, it can only be used to build real cars, and you can use it to make a lot of cars. So how do you create an instance?

class语句本身并不创建该类的任何实例。所以在类定义完成以后,可以创建类的实例,即实例化该类的对象。创建类的实例的语法如下:

ClassName(parameterlist)

参数说明

  • ClassName:是必选参数,用于指定类。
  • parameterlist:可以选参数,当创建一个类时,没有创建__init__()方法,或者当__init__()方法只有一个self参数时, parameterlist可以省略。

例如,创建上面Geese类的实例,可以使用下面代码:

创建类
class Geese:
"""大雁类"""
pass

创建实例
wildGoose = Geese()
print(wildGoose)

执行上述代码后,将显示类似以下内容的内容:

[En]

After executing the above code, something similar to the following is displayed:

从上面的执行结果中可以看出,wildGoose是Geese类的实例。

3、”魔术”方法——_ init ()

在创建类后,类通常会自动创建一个__init_()方法。该方法是一个特殊的方法,类似JAVA 语言中的构造方法。

每当创建一个类的新实例时,Python都会自动执行它。init()方法必须包含一个参数,并且必须是第一参数。self参数是一个指向实例本身的引用,用于访问类中的属性和方法。

在方法调用时会自动传递实际参数self。因此,当__init__()方法只有一个参数时,在创建类的实例时,就不需要指定参数了。

例如,下面乃然以大雁为例,并创建__init__()方法,代码如下:

创建类
class Geese:
"""大雁类"""

def __init__(self):
    print("我是大雁类")

wildGoose = Geese()

运行上面的代码,您将输出以下内容:

[En]

Run the above code and you will output the following:

【Python基础教程】类的定义和使用

常见错误

在为类创建__init__()方法时,在开发环境中运行下面的代码:

创建类
class Geese:
"""大雁类"""

def __init__():             # 构建方法
    print("我是大雁类")

wildGoose = Geese() # 创建大雁实例

运行上面的代码会引发以下异常:

[En]

Running the above code throws the following exception:

在__init__()方法中,除了self参数外,还可以自定义一些参数,参数间使用逗号”,”进行分隔。

例如,下面的代码将在创建__init__()方法时,再指定3个参数,分别是beak、wing和claw:

创建类
class Geese:
"""大雁类"""

def __init__(self, beak, wing, claw):
    print("我是大雁类!我有一下特征:")
    print(beak)
    print(wing)
    print(claw)

beak_1 = "喙"
wing_1 = "翅膀"
claw_1 = "爪"
wildGoose = Geese(beak_1, wing_1, claw_1)

运行上述代码,将显示以下结果:

[En]

Run the above code, and the following results are displayed:

4、创建类的成员并访问

类成员主要由实例方法和数据成员组成。在类中创建类的成员后,可以通过类的实例访问它。以下是详细的描述。

[En]

Class members are mainly composed of instance methods and data members. After you create a member of a class in a class, you can access it through an instance of the class. The following is described in detail.

4.1、创建实例方法并访问

所谓实例方法是指在类中定义函数。该函数是一种在类的实例上操作的函数。同__init__()方法一样,实例方法的第一参数必须是self,并且必须包含一个self参数。创建实例的方法的语法格式如下:

def functionName(self,parameterlist):
    block

参数说明

  • functionName:用于指定方法名,一般使用小写字母开头。
  • self:必要参数,表示类的实例,其名称可以是self以外的单词,使用self只是一个习惯而已。
  • parameterlist:用于指定除self参数以外的参数,各参数间使用逗号”,”进行分隔。
  • block:方法体,实现的具体功能

创建实例后,可以使用实例名称和点(.)班上的一员。要访问的操作员。具体语法格式如下:

[En]

After the instance is created, you can use the instance name and dot (.) of the class. Operator to access. The specific syntax format is as follows:

instanceName.functionName(parametervalue)

参数说明

  • instanceName:为类的实例名称
  • functionName:为要调用的方法名称
  • parametervalue:表示为方法指定对应的实际参数,其值的个数与创建实例方法中parameterlist的个数相同。

4.2、创建数据成员并访问

数据成员是指类中定义的变量,即属性,根据定义的位置可分为类属性和实例属性,具体描述如下。

[En]

Data members refer to the variables defined in the class, that is, attributes, which can be divided into class attributes and instance attributes according to the defined location, which are described below.

类属性

类属性是那些在定义类中、在函数之外的属性。类属性可以在类的所有实例之间,即在所有实例化的对象之间共享值。

[En]

Class attributes are those that are in the definition class and outside the function. Class properties can share values among all instances of the class, that is, among all instantiated objects.

例如,定义一只雁,并在这个类中定义三个属性来记录鹅的特征。代码如下:

[En]

For example, define a wild goose, and define three attributes in this class to record the characteristics of the geese. The code is as follows:

class Geese:
    """大雁类"""
    beak_1 = "喙,比较尖"  # 定义类属性(喙)
    wing_1 = "翅膀,比较大"
    claw_1 = "爪,行走自如"

    def __init__(self):
        print("我是大雁类!我有一下特征:")
        print(Geese.beak_1)   # 输出喙的属性
        print(Geese.wing_1)
        print(Geese.claw_1)

创建上面的类Geese,然后创建类的实例,代码如下:

goose = Geese()  # 实例化一个雁的对象

运行上面代码创建Geese类的实例后,将显示以下内容:

实例属性

实例属性是在类的方法中定义的属性,仅在当前实例中起作用。

[En]

An instance property is a property defined in the method of a class and acts only in the current instance.

例如,定义一个雁类Geese,在该类的__init__()方法中定义3个实例属性,用于记录雁类的特征,代码如下:

创建类
class Geese:
    """大雁类"""
    def __init__(self):
        self.beak_1 = "喙,比较尖"  # 定义实例属性(喙)
        self.wing_1 = "翅膀,比较大"
        self.claw_1 = "爪,行走自如"
        print("我是大雁类!我有一下特征:")
        print(self.beak_1)   # 输出喙的属性
        print(self.wing_1)
        print(self.claw_1)

创建上面的类Geese,然后创建类的实例,代码如下:

goose = Geese()  # 实例化一个雁的对象

运行上面代码创建Geese类的实例后,将显示以下内容:

说明

实例属性只能通过实例名称访问。如果通过类名访问实例属性,则会抛出图中所示的异常。

[En]

Instance properties can only be accessed through the instance name. If the instance property is accessed through the class name, the exception shown in the figure will be thrown.

实例的属性也可以通过实例名进行修改,与类不同的是,实例名修改实例属性后,类的其他实例中对应的实例属性值不会受到影响。

[En]

The properties of the instance can also be modified through the instance name, unlike the class, the value of the corresponding instance property in other instances of the class can not be affected after the instance property is modified by the instance name.

例如,定义一个雁类,并在__init__()方法中定义一个实例属性,然后创建两个Geese类的实例,并修改一个实例属性,最后分别输出实例属性,代码如下:

创建类
class Geese:
    """大雁类"""

    def __init__(self):
        self.beak_1 = "喙,比较尖"  # 定义实例属性(喙)
        print(self.beak_1) # Python学习交流君羊 279199867

goose1 = Geese()  # 创建Geese实例1
goose2 = Geese()  # 创建Geese实例2
goose1.beak_1 = "喙,比长鹅尖"  # 修改实例属性
print("goose1的beak_1属性:", goose1.beak_1)
print("goose2的beak_1属性:", goose2.beak_1)

运行上述代码,将显示以下内容:

[En]

Run the above code, and the following is displayed:

5、访问限制

在类的内部可以定义属性和方法,而在类的外部则可以直接调用属性或方法来操作数据,从而隐藏了类内部的复杂逻辑。但Python并没有对属性和方法的访问权限进行限制。

为了保证类内部的某些属性或方法不被外部所访问,可以在属性或方法名前面添加单下划线(_foo)、双下划线(foo)或者首尾加双下划线( foo __),从而限制访问权限。

其中,单下划线、双下划线、头尾双下划线的功能如下:

[En]

Among them, the functions of single underscore, double underscore, head and tail double underscore are as follows:

  • foo :首尾双下划线表示定义特殊方法,一般是系统定于名字,如__init__()。
  • _foo:以单下划线开头的表示protected(保护)类型的成员,只允许类本身或子类访问,但不能使用” from module impor”语句导入。

例如,创建一个Swan类,定义保护属性_neck_swan,并在__init__()方法中访问该属性,然后创建Swan类的实例,并通过实例名输出保护属性_neck_swan,代码如下:

class Swan:
    """天鹅类"""
    _neck_swan = "天鹅脖子长"  # 创建私有属性

    def __init__(self):
        print("__init__():", Swan._neck_swan)

swan = Swan()  # 创建Swan类
print("直接访问:", swan._neck_swan)

执行上述代码,显示如下:

[En]

Execute the above code, and the following is displayed:

从上面的运行结果可以看出,可以通过实例名称访问保护属性。

[En]

As can be seen from the above running results, the protection property can be accessed through the instance name.

  • __foo:双下划线表示private(私有)类型的成员,只允许定义该方法的类本身进行访问,而且也不能通过类的实例进行访问,但是可以通过”类的实例名.类名 __xxx”方式访问。

例如,创建一个Swan类,定义保护属性__neck_swan,并在__init__()方法中访问该属性,然后创建Swan类的实例,并通过实例名输出保护属性__neck_swan,代码如下:

class Swan:
    """天鹅类"""
Python源码、教程领取群 279199867
    __neck_swan = "天鹅脖子长"  # 创建私有属性

    def __init__(self):
        print("__init__():", Swan.__neck_swan)

swan = Swan()  # 创建Swan类
print("加入类名:", swan._Swan__neck_swan)
print("直接访问:", swan.__neck_swan)

运行上面的代码并输出如图所示的结果:

[En]

Run the above code and output the result shown in the figure:

从上面的运行结果可以看出:私有属性可以通过”类名.属性名”方式访问,也可以通过”实例名.类名__xxx”方式访问,但是不能直接通过”实例名.属性名”方式访问。

好了,兄弟们,今天的分享就到这结束了,最后再分享一套Python教程给大家,涵盖了常见的爬虫案例,非常详细。

Python爬虫实战100例

Original: https://www.cnblogs.com/hahaa/p/16608101.html
Author: 轻松学Python
Title: 【Python基础教程】类的定义和使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/498683/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球