Python `class` 和 `def` 之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18867494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:06:57  来源:igfitidea点击:

Differences between `class` and `def`

pythondjangouser-interface

提问by Slow learner

What is the main difference between classand defin python? Can a class in python interact with django UI (buttons)?

pythonclassdefpython之间的主要区别是什么?python中的类可以与django UI(按钮)交互吗?

回答by Aesthete

classdefines a class.

class定义一个类。

defdefines a function.

def定义一个函数。

class Foo:
    def Bar(self):
        pass

def Baz():
   pass

f = Foo() # Making an instance of a class.
f.Bar() # Calling a method (function) of that class.
Baz() # calling a free function

回答by nakedfanatic

classis used to define a class (a template from which you can instantiate objects).

class用于定义一个类(可以从中实例化对象的模板)。

defis used to define a function or a method. A method is like a function that belongs to a class.

def用于定义函数或方法。方法就像属于类的函数。

# function
def double(x):
    return x * 2

# class
class MyClass(object):
    # method
    def myMethod(self):
        print ("Hello, World")

myObject = MyClass()
myObject.myMethod()  # will print "Hello, World"

print(double(5))  # will print 10

No idea about the Django part of your question sorry. Perhaps it should be a separate question?

不知道你的问题的 Django 部分抱歉。也许它应该是一个单独的问题?