class classname: variable initializations # these tend to be class variables fct definitions
class Point:
x = 0
y = 0
def addPoint(self, p1):
newpoint = Point()
newpoint.x = self.x + p1.x
newpoint.y = self.y + p1.y
return newpoint
self is like the this pointer in Java and C++ but must
be explicitly declared. It is always passed as the first argument to
a method. If you want to access instance variables, then you must
prefix the variable's name with self as is done in the above
example. If you fail to do so, then instead of getting access to the
instance variable, you will be either reading from a local method
variable or, if using an assignment statement, creating a new local
method variable with that name.
class Stack: _top = 0
>>> class Dog:
... tricks = []
... def addTrick(self, trick):
... self.tricks.append(trick)
...
>>> smiley = Dog()
>>> ebber = Dog()
>>> smiley.addTrick("beg")
>>> ebber.addTrick("fetch")
>>> print (smiley.tricks)
['beg', 'fetch']
>>> print (ebber.tricks)
['beg', 'fetch']
If we replace the value, then the attribute becomes a local
attribute
>>> smiley.tricks = ['beg'] >>> smiley.tricks ['beg'] >>> ebber.tricks ['beg', 'fetch']See constructors for a technique that allows you to create local attributes with mutable values.
a = Point() b = Point() c = Point.addPoint(a, b) // function call c = a.addPoint(b) // method call
class Stack:
def __init__(self):
self.top = 0
self.data = []
It is also a good idea to define any instance variables
in a __init__ function and to define class variables outside
the __init__ function in the general body of the class statement.
myPoint = Point() # if the constructor takes no arguments myPoint = Point(x, y) # if the constructor takes two arguments
class Student: passThen the programmer can create instances of Student and assign attributes on an ad-hoc basis:
s = Student() s.gpa = 3.1 s.name = 'Brad'Of course one could also create a constructor for such a class that initializes a number of variables to starting values.
class DerivedClassName(BaseClassName):
.
.
.
For example:
class LabradorRetriever(Dog):
hair = 'short'
personality = ['friendly', 'good with children', 'love to fetch']
class DerivedClassName(Base1, Base2, Base3):
.
.
.