I do not understand what he wants from me:

TypeError: date_generator() missing 1 required positional argument: 'self'

 import random class format_creator: def random_string(self, string): return string[random.randint(0,len(string)-1)] def date_generator(self): hashtag_on_off = ('', '#') result = self.random_string(hashtag_on_off) return result 

Please help out friends!

 import presets_generator #название файла с проблемным классом preset = presets_generator.format_creator result = preset.date_generator() print(result) TypeError: date_generator() missing 1 required positional argument: 'self' 

This is how I call this method through a class object in another file. I get the same error. I understand that the error is that I somehow do not correctly call a function from a function of the same class.

  • In the class there should not be such code outside the methods. If you call from another method, then self.date_generator() . - insolor
  • And what do you want to do then? Create a class with static functions? Why don't you have a constructor? Instances will not be created? - suit
  • @insolor thanks for responding. I will clarify the problem: print (date_generator ()) here, for example, deleted. When calling this function from the main program, I also get "missing 1 required positional argument: 'self'". In short, I can’t call random_string () from date_generator () - Dmitry Sharko
  • Calling class functions (methods) is always through an object or through a class. - insolor
  • @suit, no constructor required. You just need a set of functions. I need to call random_string () from date_generator (). This is where I get an error with self. I call this class and its date_generator () method from the main code. - Dmitry Sharko

1 answer 1

If you need a class with auxiliary functions, the methods are best done static:

 class format_creator: @staticmethod def random_string(string): return string[random.randint(0,len(string)-1)] @classmethod def date_generator(cls): hashtag_on_off = ('', '#') result = cls.random_string(hashtag_on_off) return result 

classmethod needed in order to be able to access from this method to other methods of this class. If this is not required, then all methods should be made staticmethod .

Call:

 result = format_creator.date_generator() print(result) 
  • Thank you #stackoverflow gods for help. and @suit for a very clear explanation of the mechanic! - Dmitry Sharko