-1

I am trying to understand class properties in Python OO (Object Oriented).

Let's say I have the following code.

    class Testing():
        surname = "Doe"

        def __init__(self):
            print(surname)
            

If we print surname, as shown above, it will throw the following error: NameError: name 'surname' is not defined. So, how is this class property accessible from outside or inside the class?

Anas Yusef
  • 169
  • 2
  • 14

2 Answers2

2

surname is only available inside the __init__ method. If you want to access it anywhere else you should do self.surname = 'Doe' or Testing.surname = 'Doe'. Note that self is a reference to the instance.

Usually class attributes are declared inside the class like this:

class Testing:
     surname = 'Doe'

You could access them and/or reassign them by using Testing.surname.

Lion Wild
  • 51
  • 3
0

Your code must read as

    class Testing():
        surname = "Doe"

        def __init__(self):
            print(self.surname)  # <<< note `self.` prefix
jno
  • 997
  • 1
  • 10
  • 18