Home > Mobile >  TypeError: Missing 1 required positional argument: 'self' Anybody?
TypeError: Missing 1 required positional argument: 'self' Anybody?

Time:02-01

I keep on getting issues with a part of my code. Anybody has some idea how to tackle it? Python - Selenium

def openStories(self):
    bot=self.bot
    bot.find_element_by_class_name('OE30K').click() 

CodePudding user response:

Hope you understand the difference between defining a method within a class and a function outside a class.

class MyClass:
    foo = "HELLO!"

    def openStories1(self):
        # Here self is an instance of MyClass
        print(self.foo)

def openStories2(self):
    # Here self is just an object.
    print(self.foo)

# Can be called without explicitly passing an argument, since self refers to the instance1
instance1 = MyClass()
instance1.openStories1()

# When defining outside a class you will need to pass the instance explicitly.
openStories2(instance1)

# Raises error since this function cannot be accessed through the instance because it's not defined in the class.
instance1.openStories2()

Outputs:

HELLO!
HELLO!
Traceback (most recent call last):
  File "scratch_6.py", line 18, in <module>
    instance1.openStories2()
AttributeError: 'MyClass' object has no attribute 'openStories2'

CodePudding user response:

In Python self is used this way:

class MyClass:
    def __init__(self, name: str, age: int) -> None: # constructor
        self.age = age # self is the object that the constructor is initializing
        self.myMethod(name) # You can call methods passing the instance itself as argument, the argument 'self' is the instance
    def myMethod(self, name: str) -> None:
        self.name = name

The self variable represents the instance itself.

>>> my_object = MyClass()
>>> my_object.myMethod('myName')
>>> print(my_object.name)
'myName'

The self argument is the instance on which the method is called.

  •  Tags:  
  • Related