-2

I am new to OOP in Python.

As the title suggests, I am unsure as to how the __init__ method can assign attributes to an object of a given class if the attributes have not been defined in the constructor.

I tried some experimenting around with the following code:

class initPlane:
    def __init__(self, manufacturer)
        print(manufacturer)
    def get_manufacturer(self):
        return self.manufacturer

cessna = initPlane("Cessna")
print(cessna.get_manufacturer())

Obviously I received the "AttributeError" that the class initPlane has no attribute manufacturer when the method 'get_manufacturer' tries to receive the manufacturer attribute of the instance cessna.

To fix this it is clear that I need to create the manufacturer attribute by altering the code of the constructor as follows:

def __init__(self, manufacturer)
        self.manu = manufacturer
        print(manufacturer)

What is confusing... is that I do not understand how I am able to print the manufacturer attribute, without creating the attribute in the first place. The following code returns a result without errors.

class initPlane:
    def __init__(self, manufacturer)
        print(manufacturer)
cessna = initPlane("Cessna")

I do not know how the method is able to print the manufacturer, without me first creating the attributes within the constructor.

quamrana
  • 33,740
  • 12
  • 54
  • 68
Perthie
  • 1
  • 2
  • 2
    Because they print the things you pass into the constructor, not any attributes of the instance / class. `print(self.manufacturer)` fails as well. – luk2302 May 13 '22 at 12:15
  • 1
    Assigning the attribute creates it. Period. Done. That simple. Doing it in `__init__` just ensures it's happening at class instantiation time, so it's guaranteed to exist on the instance. – deceze May 13 '22 at 12:16
  • Still confused. If assigning the attributes creates it, then why cannot I return the manufacturer attribute in the get_manufacturer method. If they exist as attributes, then why can't get_manufacturer return the manufacturer? – Perthie May 13 '22 at 12:20
  • 2
    If you don't assign a `self.manufacturer` attribute, then it doesn't exist. `manufacturer` the *function parameter* isn't the same as a `self.manufacturer` *attribute*. – deceze May 13 '22 at 12:22
  • because you never assigned it in the first snippet, only `self.something = something` does that. And `something` is entirely different compared to `self.something`. – luk2302 May 13 '22 at 12:22

0 Answers0