Classes in Python

Classes allow creating objects with properties and methods in Python.

See below the definition and use of a class:

class TestCalculator:
    def __init__(self, x):
        self.x = x
       
    def multiplyBy(self, y):
        if not isinstance(y, float):
            raise Exception("Wrong argument type, only float accepted")
        self.result = self.x * y
        return self.result
   
    def __str__(self):
        return 'x was %f, result is %f' % (self.x, self.result)
   
   
X = TestCalculator(2)
Result = X.multiplyBy(3.)
print(X)
#x was 2.000000, result is 6.000000
#Exception: Wrong argument type, only float accepted
 
try :
    Result = X.multiplyBy(3)
except Exception as err:
    print(err)
Matthieu Liatard
Remember this!
Remember this
Play!
Take a quizz on this subject
Close

Hello :)
At Question-Player, we want to share more knowledge and help you never forget anything ever. And for free.

To show us your support, you can create an account:

Login / Create an account
Rate this article :
1
2
3
4
5

Up next

Related posts