pass语句在函数中的作用?

2024-05-14 03:44:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个面向对象编程的新手。定义一个类之后,我们只需创建对象,并尝试访问类中的不同变量和函数。在下面的代码中,我想知道为什么我们还要在函数中再次提到类Dataset,其次pass语句的作用是什么?你知道吗

def read_data_set():
    class Dataset:
        pass
    data_sets = Dataset()
    return(data_sets)
    #Function call
x=read_data_set()
print(x)

Tags: 函数代码readdatareturn定义defsets
3条回答

它基本上什么都不做。你知道吗

它通常用作占位符,就像在代码中一样;您会注意到,如果没有pass,代码根本无法运行。你知道吗

class SomeClass:
    pass # to be filled

这是因为Python期望某些东西在SomeClass的定义下,但如果为空,则会引发IndentationError。你知道吗

class SomeClass:
    # to be filled <--- empty
other_function() # <--- IndentationError

当您不想做任何事情时,它也与try-except一起使用:

try:
    some_stuff()
except SomeException:
    pass # I don't mind this

为什么我们要在函数中两次提到类数据集?

第一次

class Dataset:
    pass

类已定义

第二个是:

data_sets = Dataset()

将创建此类(对象)的实例。正如OP写的:

After defining a class we simply create objects.

因为class只是一个python语句,所以它可以在任何地方使用:包括函数体,比如在本例中。因此在这里,每次调用函数read_data_set()时都会定义类,如果没有调用,则根本不定义。你知道吗


pass语句的作用是什么?

在这个例子中

class Dataset:
    pass

pass语句意味着定义一个没有添加成员的类。这意味着类及其对象只包含一些由任何类从object派生的“默认”函数和变量(即方法和字段)。你知道吗


通常,当您引入一个新的块并想将其留空时,会使用pass

expression:
    pass 

必须在块中至少包含一条指令,这就是为什么有时需要pass来表示不想在块中执行任何操作。函数也是如此:

def do_nothing():
    pass  # function that does nothing

循环:

for i in collection:  # just walk through the collection
    pass              # but do nothing at each iteration

异常处理:

try:
    do_something()
except SomeException:
    pass    #  silently ignore SomeException

上下文管理器:

with open(filename):    # open a file but do nothing with it
    pass

pass什么也不做,它只是使Python缩进正确。你知道吗


假设你想创建一个空函数,比如:

def empty_func():

empty_func()  # throws IndentationError

让我们试着在里面放一条评论:

def empty_func_with_comment():
    # empty

empty_func_with_comment()  # throws IndentationError

要使其工作,我们需要使用pass来修复压痕:

def empty_func_with_pass():
    pass

empty_func_with_pass()  # it works 

相关问题 更多 >