Dezert
Dezert

Reputation: 97

__init__() missing positional argument when calling class

I am trying to figure out why the init() is missing one argument, in this case speed when 3 arguments have been given in the line plane = Mywork.__init__( 'boeing', 747, 890)

Here is the full code, I presume I didnt do something right about the first argument just being put down as a string and not specifying that anywhere even though I used str?

All I want to happen is for the code to execute def str and run.

Code:

class Mywork(object):

    def __init__(self, manufacturer, model, speed): #Aircraft
        self.manufacturer = manufacturer
        self.model = model
        self.speed = speed

    def __str__(self):
        return 'This is a {self.manufacturer} {self.model}'.format(self=self)

    def run(self):
        print('Works')
        print(self.__str__())

plane = Mywork.__init__( 'boeing', 747, 890)

if __name__ == '__main__':
    Mywork()

Upvotes: 0

Views: 111

Answers (2)

Errol
Errol

Reputation: 610

if __name__ == '__main__':
    plane = Mywork('boeing', 747, 890)
    print(plane)

OUTPUT:

>>This is a boeing 747

Upvotes: 0

chepner
chepner

Reputation: 532268

You can't call __init__ directly without first creating an instance to pass as the first argument. The following is legal, though no one would ever write code like this:

plane = Mywork.__new__(Mywork, 'boeing', 747, 980)
Mywork.__init__(plane, 'boeing', 747, 980)

What you want is almost certainly

class Mywork(object):
    ...

plane = Mywork('boeing', 747, 890)
...

You also don't really ever call __str__ explicitly; you let str do that when an instance of your class is passed as an argument.

print(self.__str__())  # No!
print(str(self))  # Better
print(self)  # Best; print() already calls str as necessary to convert its arguments

Upvotes: 1

Related Questions