1

I have a simple class A that gets the name from users.

class A:
   def __init__(self, name = ''):
       self.name = name

Then I want to create a class B that prints out this name. I tried:

class B:
    def print_name(printing_name = A.name):
        print(printing_name)

Then I call these methods:

m1 = A("x")
B.print_name(m1)

This returns the error

Traceback (most recent call last):
  File "so.py", line 5, in <module>
    class B:
  File "so.py", line 7, in B
    def print_name(printing_name = A.name):
AttributeError: class A has no attribute 'name'

I know that I did not assign a class variable in the class A, and thus the name attribute goes with specific instances, not the entire class. However, the name attribute has to connect with every specific instance because it changes from the case to case. Then how should I get this name in class B?

1
  • 1
    self.name here is an instance property rather than a class attribute. What did you try to achieve here? Commented Oct 23, 2017 at 23:31

4 Answers 4

3

Change your class B to this:

class B:

    @staticmethod
    def print_name(obj):
        print(obj.name)

The print_name method probably should be decorated as a "static method". The property "name" of self is an instance attribute which can not be referred directly from the class itself.

Sign up to request clarification or add additional context in comments.

Comments

1

That's correct: name is an instance attribute, not a class attribute. IN this case, m1 has a name, but class A does not. You need to access the name of the input parameter, not attempt to print a class attribute.

You also need to make B.print_name a class function, since you're not calling it from an instance of B.

class B:

    @staticmethod
    def print_name(inst):
        print(inst.name)

Output:

x

Comments

1

Edit: The answers suggesting @staticmethod are ideal if you understand what it does.

class A:
    def __init__(self, name = ''):
        self.name = name

class B:
    def __init__(self):
        pass
    def print_name(self, var):
        print (var.name)

Output:

>>> m1 = A("X")
>>> b = B()
>>> b.print_name(m1)
X
>>>

Comments

0

In this instance A is the name of the class, and you should not give it as the default argument for calling the print_name method. Have a look at keyword arguments for Python, and you will see that what you have written actually means that you have the default value set to the .name property of the class A, which does not exist unless the class is instantiated (i.e. an object is created of the class).

Your B class should read:

class B:
    def print_name(printing_object):
        print(printing_object.name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.