As per your comment, I see you are using Python 2. In Python 2.2 they introduced "New-style" classes, but kept "Classic" classes for backwards-compatibility reasons. In Python 3.0 or newer, classic classes are gone - every class is a new-style class (regardless of syntax).
For python 2.2-2.7, syntactically a new-style class is declared by subclassing from object
explicitly (unless it has a different parent class):
class MyStuffNew(object):
a=1
while omitting the object
reference creates a classic class:
class MyStuffClassic():
a=1
Functionally, they work almost the same, but there are a few differences between them in the builtin language definitions. For example, New-style classes introduced a builtin class method __mro()__
(method resolution order) which is used by the interpreter to work out which method (in the class inheritance heirarchy) you meant to call. This inbuilt method is missing in old-style classes (and the method resolution order is different, which can lead to some unexpected behaviour). For more information about New-style vs Classic classes, please read this Python Wiki page.
As mentioned above, in Python3 or above, the syntax used doesn't matter; all classes are new-style. However, many coders will use the class MyClass(object):
syntax to maintain code compatibility with Python2.7. - Please see this answer.
In any version of the Python language, class MyChildClass(ParentClass):
defines an inheritance relationship - MyChildClass
is a child of ParentClass
and will inherit all of its methods and fields.
The self
is the way Python knows this is a member method and not a static function of your class. You can only access member fields and methods from within your class by using self.field
and self.myMethod(var1,var2)
, etc.
When you actually call these functions from other places in your code, you don't pass a value to self
- it is the variable that you are using. For example:
stuff = MyStuff()
stuff.apple()
# outputs "I AM CLASSY APPLES!"
print stuff.tangerine
# outputs "And now a thousand years between"
stuff.tangerine = "Something else."
print stuff.tangerine
# outputs "Something else."
stuff2 = MyStuff()
print stuff2.tangerine
# outputs "And now a thousand years between"
If you don't include self
in the method definition, calling mystuff.apple()
will result in a runtime error because implicitly it's the same thing as calling MyStuff.apple(mystuff)
- passing the instance of your MyStuff
class into the apple function.