-1

I have this code

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

  @classmethod
  def from_classmethod(cls, name):
    return cls(name)

p = Person.from_classmethod("Moctar")
p.name

But it shows the following error:

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

What could be going wrong here, or am i using wrongly the python @classmethod feature ?

moctarjallo
  • 1,479
  • 1
  • 16
  • 33
  • 5
    `self.name = name` - you have to assign value to create variable `self.name`. If you do only `self.name` then it tries to get value from `self.name` which not exist yet. – furas May 19 '19 at 00:09
  • Your code doesn't produce that error. Can you post the code that does? – Blender May 19 '19 at 03:06

1 Answers1

0

As @furas says, what I think you want is:

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

  @classmethod
  def from_classmethod(cls, name):
    return cls(name)

p = Person.from_classmethod("Moctar")
print(p.name)

Result:

Moctar

It is the assignment to self.name that creates that attribute on the instance of Person that you are creating.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44