Are classes necessary for creating meth开发者_如何学Pythonods (defs) in Python?
No. However, def
's which aren't part of a class are usually called functions, not methods - but they are exactly the same thing, aside from not being associated with a class.
def myFunction(arg1, arg2):
# do something here
No, you can create functions using def
without having to wrap them in classes.
If you are coming from a Java or C# background - where a class is required - you may want to read over An Introduction to Python: Functions or a similar article to understand how to work with functions in Python, as the language provides many other features such as first-class functions, returning multiple values, anonymous functions, etc.
It depends on your definition of "method".
In some sense, no, classes aren't necessary for creating methods in Python, because there are no methods anyway in Python. There are only procedures (which, for some strange reason, are called functions in Python). You can create a procedure anywhere you like. A method is just syntactic sugar for a procedure assigned to an attribute.
In another sense, yes, classes are necessary for creating methods. It follows pretty much from the definition of what a method is in Python: a procedure stuck into a class's __dict__
. (Note, however, that this means that you do not have to be inside a class definition to create method, you can create a procedure anywhere and any way you like and stick it into the class afterwards.)
[Note: I have simplified a bit when it comes to exactly what a method is, how they are synthesized, how they are represented and how you can create your own.]
精彩评论