Define class in python

894    Asked by leahD’Costa in Data Science , Asked on Nov 13, 2019
Answered by leah D’Costa

 In python, we use the keyword “Class” to define any class the same as we use “def” while defining a function. Below is a simple example of how we create a class in python:

class My Class:
    '''This is a test class'''
    Pass

Whenever we create any class its namespace gets created where we define all its attributes. The attribute may be functions or data. Some built-in attributes will also be there like __doc__, which returns the docstring of that class. Run below code and see what docstring is

My Class.__doc__

Whenever you define any class in python its object gets created with the same name, which helps you to access all its attributes. See below example:

class My Class 2:

 "This is my second class"
 a = 50 def func(self):

  print('Janbask Training')

print(MyClass2.a)
# Output: 50
print(MyClass2.func)
# Output:
MyClass2().func()
#Output: Janbask Training
print(MyClass2.__doc__)
# Output: 'This is my second class'

Your Answer

Interviews

Parent Categories