Constructors, Attributes & Objects

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.

class MyClass:
    "This is my second class"
    a = 10
    def func(self):
        print('Hello')
        
# Output: 10
print(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:

class MyClass:
    "This is my second class"
    a = 10
    def func(self):
        print('Hello')

# create a new MyClass
ob = 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: Hello
ob.func()

Constructors in Python:

class ComplexNumber:
    def __init__(self,r = 0,i = 0):
        self.real = r
        self.imag = i

    def getData(self):
        print("{0}+{1}j".format(self.real,self.imag))

# Create a new ComplexNumber object
c1 = ComplexNumber(2,3)

# Call getData() function
# Output: 2+3j
c1.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:

class ComplexNumber:
    def __init__(self,r = 0,i = 0):
        self.real = r
        self.imag = i

    def getData(self):
        print("{0}+{1}j".format(self.real,self.imag))

# Create a new ComplexNumber object
c1 = ComplexNumber(2,3)

# Call getData() function
# Output: 2+3j
c1.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

c1 = ComplexNumber(2,3)
del c1.imag
c1.getData()

del ComplexNumber.getData
c1.getData()

c1 = ComplexNumber(2,3)
del c1.imag
c1.getData()

#We can even delete the object itself, using the del statement.
c1 = ComplexNumber(1,3)
del c1

Last updated