In python, you define a class as follows:
class Basket: # Always remember the *self* argument def __init__(self,contents=None): self.contents = contents or  def add(self,element): self.contents.append(element) def print_me(self): result = "" for element in self.contents: result = result + " " + `element` print "Contains:"+result
Some new things:
- All methods (functions in an object) receive an additional argument at the start of the argument list, containing the object itself. (Called
selfin this example, which is customary.)
- Methods are called like this:
- Some method names, like
__init__(with two underscores before and after), are pre-defined, and mean special things.
__init__is the name of the constructor of the class, i.e. it is the function that is called when you create an instance.
- Some arguments can be optional and given a default value (as mentioned before, under the section on functions). This is done by writing the definition like:
def spam(age=32): ...
spamcan be called with one or zero parameters. If none is used, then the parameter
agewill have the value 32.
- “Short circuit logic.” This is a clever bit… See below.
- Backquotes convert an object to its string representation. (So if
elementcontains the number 1, then `
element` is the same as
'element'is a literal string.)
- The addition sign
+is used also for concatenating lists, and strings are really just lists of characters
No methods or member variables are private or protected in python, at the most, you can have some naming conventions which will offer the variable some privacy.
Short Circuit Logic:
All values in Python can be used as logic values. Some of the more “empty” ones, like
Nonerepresent logical falsity, while most other values (like
"Hello, world") represent logical truth.
Now, logical expressions like
a and b are evaluated like this: First, check if
a is true. If it is not, then simply return it. If it is, then simply return
b (which will represent the truth value of the expression.) The corresponding logic for
a or b is: If
a is true, then return it. If it isn’t, then return
So, to actually make a
Basket and to use it (i.e. to call some methods on it) we would do something like this:
b = Basket(['apple','orange']) b.add("lemon") b.print_me()
That is all. You know all the basics now. There is a lot more to learn. We haven’t even scratched the surface as yet.
To learn more, you can go to the python IDLE and press F1. A help window will open and all that you need will probably be given in there.