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
Differences between `class` and `def`
提问by Slow learner
What is the main difference between class
and def
in python? Can a class in python interact with django UI (buttons)?
pythonclass
和def
python之间的主要区别是什么?python中的类可以与django UI(按钮)交互吗?
回答by Aesthete
class
defines a class.
class
定义一个类。
def
defines 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
class
is used to define a class (a template from which you can instantiate objects).
class
用于定义一个类(可以从中实例化对象的模板)。
def
is 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 部分抱歉。也许它应该是一个单独的问题?