0
class student:
    ''' Doc String for student class'''
    clgname='#########'
    def __init__(self,name,rNo,branch):
        self.name=name
        self.rNo=rNo
        self.branch=branch
        return None
    @classmethod
    def classMethodexp(cls):
        cls.clgname='halva clg'

if __name__=='__main__':
    obj=student(name='Halv',branch='ece',rNo=12345)
    print(obj.__dict__)
    obj.__init__(name='******',branch='ece',rNo=12345)
    print(obj.__dict__)

output:

{'name': 'Halv', 'rNo': 12345, 'branch': 'ece'}
{'name': '******', 'rNo': 12345, 'branch': 'ece'}

I heard a few languages don't allow constructor call once an object is created, then why does Python allow it??

  • 2
    `why python allows it??` - Because it does? – wwii Jan 16 '21 at 16:45
  • Please update the indentation of your code. Python is very sensitive to indentation, as are python programmers. – quamrana Jan 16 '21 at 16:45
  • [Formatting help](https://stackoverflow.com/editing-help)... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii Jan 16 '21 at 16:46
  • 1
    Why? → Because there's no need to explicitly disallow that. Use it at your own risk. – iBug Jan 16 '21 at 16:47
  • Because objects in Python are mutable and you can change the attributes. See this question to make objects immutable: https://stackoverflow.com/questions/4828080/how-to-make-an-immutable-object-in-python – rajah9 Jan 16 '21 at 16:52
  • This is what makes *inheritence* possible. You call parent class' `__init__` method to initialize your child class. – Asocia Jan 16 '21 at 16:56
  • 1
    Why not? What is the problem with calling the `__init__` hook again? – juanpa.arrivillaga Jan 16 '21 at 17:58
  • @Asocia well, that would be distinct from the OPs example. In inheritance, typically, distinct `__init__`s are called each only once – juanpa.arrivillaga Jan 16 '21 at 18:00
  • 4
    Note, in Python, `__init__` is technically an "initializer", whereas `__new__` is a constructor, or rather, object construction involves both – juanpa.arrivillaga Jan 16 '21 at 18:09

0 Answers0