How Do You Instantiate a class in Python?

Problem scenario
You inherited code from a different programmer. You want to test out an object. How do you create an object of a pre-made class?

Solution
Look at how many variables the class has. Take this code for example:

class Cartesian(object):
    def __init__(self,a = 0,b = 0):
        self.a = a
        self.b = b

    def distance(self):
        return (self.a**2 + self.b**2) ** 0.5 # Pythagorean theorem.

You find variables "a" and "b". So you should use two arguments when you create the object. Here is a line of code that should appear in the same program beneath the class definition:

contint = Cartesian(4, 1)

To test it out, place this line of code at the bottom:

print(contint.distance())

This program may show how it all works more clearly:

class Cartesian(object):
    def __init__(self,x = 0,y = 0):
        self.x = y
        self.y = x

    def distance(self):
        return (self.x - self.y)

contint = Cartesian(4, 1)

print(contint.distance())

Leave a comment

Your email address will not be published. Required fields are marked *