在这里,解释了 Python 中 方法和函数之间的主要区别。 Java也是一种面向对象(OOP)语言,但其中没有函数之的概念。 但是 Python 既有方法的概念,也有函数的概念。

Python方法

  • 方法按其名称调用,但它与对象相关联(从属)。
  • 方法被隐式传递给调用它的对象。
  • 它可能会或可能不会返回任何数据。
  • 方法可以对相应类包含的数据(实例变量)进行操作。

Python中的基本方法结构:

# Basic Python method
class class_name
    def method_name () :
        ......
        # method body
        ......

Python3 用户定义的方法:

# Python 3 User-Defined Method
class ABC :
    def method_abc (self):
        print("I am in method_abc of ABC class. ")

class_ref = ABC() # object of ABC class
class_ref.method_abc()

运行结果:

I am in method_abc of ABC class

Python3内置方法:

import math

ceil_val = math.ceil(15.25)
print( "Ceiling value of 15.25 is : ", ceil_val)

运行结果:

Ceiling value of 15.25 is :  16

函数

  • 函数是代码块,也按其名称调用。
  • 函数可以有不同的参数,也可以根本没有。如果传递了任何数据(参数),则显式传递它们。
  • 它可能会或可能不会返回任何数据。
  • 函数不处理类及其实例概念。

Python中的基本函数结构:

def function_name ( arg1, arg2, ...) :
    ......
    # function body
    ......

Python3 用户定义函数:

def Subtract (a, b):
    return (a-b)

print( Subtract(10, 12) ) # prints -2
print( Subtract(15, 6) ) # prints 9

运行结果:

-2
9

Python3 内置函数:

s = sum([5, 15, 2])
print( s ) # prints 22

mx = max(15, 6)
print( mx ) # prints 15

运行结果:

22
15

方法与函数的区别

  • 简单地说,函数和方法看起来很相似,因为它们以几乎相似的方式执行,但关键区别在于“类及其对象”的概念。
  • 函数只能通过其名称调用,因为它是独立定义的。 但是方法不能只通过它的名字来调用,需要通过定义它的那个类的引用来调用这个类,即方法是在一个类中定义的,因此它们依赖于那个类。