Home > Blockchain >  Why in python it give me an error about the class?
Why in python it give me an error about the class?

Time:10-18

class mylabel:
    def __init__(self,testo):
       self.testo = testo
    def get_text(self):        
       testo = input ("Cosa vuoi scrivere?:\n")
       return testo
 
label=mylabel.get_text()

The terminal give me this error:

mylabel.get_text() missing 1 required positional argument: 'self'

CodePudding user response:

There is a difference between a class and an object (or instance) of that class.

In your example mylabel is a class but not an object. You need to create an instance of that class before you can use it.

mylabel_instance = mylabel(testo='Foobar')
label=mylabel.get_text()

Please let me give you some more advises. Try to follow the minimal PEP8 coding guideline rules e.g. for nameing. A class allways starts with an upper case letter in camel case. In your example mylabel should be named MyLabel.

And the instance or on object (or a variable) is starts with a lower case letter. And it is recommended to avoid camel case in variable names.

Your code and your type of question indicates that you are an absolute beginner to Python. Keep in mind that stackoverflow does not free you from the need to search for yourself for answers and to read tutorials, documentation and books.

CodePudding user response:

get_text doesn't use any instance or class data - its only job is to prompt the user for data. That's what a static method is for. A static method is accessed through the class namespace and can be overridden by subclasses but otherwise behaves the same as a regular module level function.

class mylabel:
    def __init__(self,testo):
       self.testo = testo

    @staticmethod
    def get_text():        
       testo = input ("Cosa vuoi scrivere?:\n")
       return testo
 
label=mylabel.get_text()

In your code, get_text is an instance method and requires an instance of the class for access:

label = mylabel().get_text()

but that includes the extra cost of creating the instance.

  • Related