



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to object-oriented programming in python, focusing on defining and instantiating custom classes with instance variables and methods. Topics include creating a simple mypoint class, initializing variables, and using special method __init__.
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!




A first example of a new class: With variables only, no methods Making a new class: class MyPoint: ”””This class represents a 2-dimensional point””” x = None # integer: x-axis value y = None # integer: y-axis value This defines a constructor function MyPoint() that you can use to make an object of the new class:
myvar = Point() myvar.x = 0 myvar.x 0 Once myvar is a variable of type MyPoint, it has associated instance variables x and y that you can read and write using the dot notation. Making your own types: classes Different instances of the same data type can hold different values in their instance variables. a = MyPoint() a.x = 0 b = MyPoint() b.x = 2 a.x 0 b.x 2
class MyPoint: x = None y = None def printme(self): print “x:”, self.x, “y:”, self.y Note that the method definition looks (almost) like the function definitions you have seen before, but it is within the block of “class MyPoint”.
class MyPoint: x = None y = None def printme(self): print “x:”, self.x, “y:”, self.y The parameter ‘self’ of the MyPoint method printme is the object to which the method belongs. So, self.x is the x instance variable of the object to which the printme method belongs.
class MyPoint: x = None y = None def printme(self): print “x:”, self.x, “y:”, self.y When you call the ‘printme’ method, you don’t need to provide the ‘self’ parameter. Python does that for you:
a = Point() a.x = 3 a.y = 5 a.printme() x: 3 y: 5
There is a special method init. If you define it, it is called when you make a new object of the given class. class MyPoint: x = None y = None def init(self, new_x, new_y): self.x = new_x self.y = new_y
a = MyPoint(3, 5) a.x 3