sujit regmi
sujit regmi

Reputation: 5

AttributeError: 'person' object has no attribute 'name'

class Name():
    def full_name(self):
        self.firstname='[no name]'
        self.lastname='[no name]'

class person:
    def detail(self):
        self.name=Name()
        self.eye='[no eye]'
        self.age=-1

myperson=person()
myperson.name.firstname='apple'
myperson.name.lastname='regmi'
myperson.name.firstname='cat'
print(myperson.name.firstname)

i could not find out why iam getting line 13, in myperson.name.firstname='apple' AttributeError: 'person' object has no attribute 'name'

Upvotes: 0

Views: 3236

Answers (1)

Michael Delgado
Michael Delgado

Reputation: 15432

It seems like you're hoping to set the name, eye, and age attributes as defaults when you create any person object. If that's the case, detail should really be replaced with __init__, e.g.:

class person:
    def __init__(self):
        self.name=Name()
        self.eye='[no eye]'
        self.age=-1

A class's __init__ method defines how objects should be initialized when they are created. You don't need to call this method explicitly; instead, it is automatically run when you create an instance of a class:

# create an instance of persion, call
# `person.__init__()`, and assign the result
# to `myperson`:
myperson = person()

Now you should be able to reference and assign the attributes:

myperson.name.firstname='apple'
myperson.name.lastname='regmi'
myperson.name.firstname='cat'

Similarly, name.full_name should probably be name.__init__.

Note that by convention, classes in python usually use TitleCase, so this class would typically be named Person; likewise, name would be Name.

Upvotes: 1

Related Questions