Like function definitions begin with the keyword def, in Python, we define a class using the keyword class.
The first string is called docstring and has a brief description about the class. Although not mandatory, this is recommended.
There are also special attributes in it that begins with double underscores (). For example, doc__ gives us the docstring of that class.
classMyClass:"This is my second class" a =10deffunc(self):print('Hello')# Output: 10print(MyClass.a)# Output: <function MyClass.func at 0x0000000003079BF8>print(MyClass.func)# Output: 'This is my second class'print(MyClass.__doc__)
10
<function MyClass.func at 0x000001FE651F8948>
This is my second class
Defining a new Object:
classMyClass:"This is my second class" a =10deffunc(self):print('Hello')# create a new MyClassob =MyClass()# Output: <function MyClass.func at 0x000000000335B0D0>print(MyClass.func)# Output: <bound method MyClass.func of <__main__.MyClass object at 0x000000000332DEF0>>print(ob.func)# Calling function func()# Output: Helloob.func()
Constructors in Python:
classComplexNumber:def__init__(self,r=0,i=0): self.real = r self.imag = idefgetData(self):print("{0}+{1}j".format(self.real,self.imag))# Create a new ComplexNumber objectc1 =ComplexNumber(2,3)# Call getData() function# Output: 2+3jc1.getData()# Create another ComplexNumber object# and create a new attribute 'attr'c2 =ComplexNumber(5)c2.attr =10# Output: (5, 0, 10)print((c2.real, c2.imag, c2.attr))# but c1 object doesn't have attribute 'attr'# AttributeError: 'ComplexNumber' object has no attribute 'attr'c1.attr
2+3j
(5,0,10)
AttributeError Traceback (most recent call last)
in 24 # but c1 object doesn't have attribute 'attr' 25 # AttributeError: 'ComplexNumber' object has no attribute 'attr' ---> 26 c1.attr
AttributeError: 'ComplexNumber' object has no attribute 'attr'
Deleting Attributes & Objects:
classComplexNumber:def__init__(self,r=0,i=0): self.real = r self.imag = idefgetData(self):print("{0}+{1}j".format(self.real,self.imag))# Create a new ComplexNumber objectc1 =ComplexNumber(2,3)# Call getData() function# Output: 2+3jc1.getData()# Create another ComplexNumber object# and create a new attribute 'attr'c2 =ComplexNumber(5)c2.attr =10# Output: (5, 0, 10)print((c2.real, c2.imag, c2.attr))# but c1 object doesn't have attribute 'attr'# AttributeError: 'ComplexNumber' object has no attribute 'attr'#c1.attrc1 =ComplexNumber(2,3)del c1.imagc1.getData()del ComplexNumber.getDatac1.getData()c1 =ComplexNumber(2,3)del c1.imagc1.getData()#We can even delete the object itself, using the del statement.c1 =ComplexNumber(1,3)del c1