acclivity

pyOOP-Class-Methods

Jun 8th, 2022 (edited)
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. # This is my first solution to writing a class for counting vowels in a string
  2. # A second solution follows this one, and is perhaps neater / more efficient
  3.  
  4. # Please bear in mind that this is the first time I have ever attempted to write class methods LOL
  5.  
  6. class UserMainCode(object):
  7.     @classmethod
  8.     def countvowels(cls, vowels, in1):
  9.    # write code after this line only
  10.         count = 0
  11.         for char in in1:
  12.             if char in vowels:
  13.                 count += 1
  14.         return count
  15.  
  16.     def __init__(self):
  17.         pass                    # no parameters are passed when initialising the method, so we only need "pass" here
  18.  
  19.  
  20. obj = UserMainCode()            # Create an instance of the class, passing no parameters
  21.  
  22.  
  23. allvowels = 'aeiou'
  24. input1 = 'fggsartuioio'
  25.  
  26. # Call the vowel counting method, passing it the vowel string, and the string to be analysed
  27. vowel_count = obj.countvowels(allvowels, input1)
  28. print(vowel_count)
  29.  
  30. #------------------------------------------------
  31. # Here is my second and possibly better solution
  32.  
  33. class UserMainCode(object):
  34.     @classmethod
  35.     def countvowels(cls, in1):
  36.    # write code after this line only
  37.         count = 0
  38.         for char in in1:
  39.             if char in cls.vowels:      # the class already knows what vowels are
  40.                 count += 1
  41.         return count
  42.  
  43.     @classmethod                    # here we define a second class method
  44.     def __init__(cls, vowels):      # the object instantiation defines the set of vowels
  45.         cls.vowels = vowels         # create a class attribute that defines what vowels are
  46.  
  47. allvowels = 'aeiou'
  48. myobject = UserMainCode(allvowels)       # Make an instance of the class, telling it the vowels
  49.  
  50. input1 = 'fggsartuioio'
  51. vowel_count = myobject.countvowels(input1)  # Call the class counting method, passing just the string to analyse
  52.                                             # We only need to pass the string to be counted
  53.                                             # as the class already knows what vowels are
  54.  
  55. print(vowel_count)
  56.  
  57. # output
  58. # 6
Add Comment
Please, Sign In to add comment