Set and call object instance in Python

Question:

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…

Asked By: Mr Agent Smith

||

Answers:

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
Answered By: Mario Sessa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.