0
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'

sujit regmi
  • 5
  • 1
  • 2
  • Obviously you can't access `myperson.name` because you didn't run `myperson.detail` at first so `myperson.name` have not been defined yet. – Yang HG May 21 '20 at 06:04

1 Answers1

1

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.

Michael Delgado
  • 13,789
  • 3
  • 29
  • 54