Home > Mobile >  Set and call object instance in Python
Set and call object instance in Python

Time:11-14

Not sure what I am doing wrong here when trying to initiate instance of object and set a name to the instance...

class Person:
    def Person(self, name):
        def __init__(self, name):
            self.name = name

m = Person.Person('James')

m.name

Any help with an explanation?

I've personally not encountered a situation where the init function is nested beneath a parent function...

CodePudding user response:

The problem here is correlated to the function definition. Basically, you are calling Person function that define but doesn't call the init one. So, you can solve like that:

class Person:
    def __init__(self, name):
        self.name = name
    
m = Person('James')
m.name
  • Related