0

So i am writing this very simple encryptor and decryptor in python.I understand it procedural way but i want to make a class of it. Here is the code

class Encrypt():
    def __init__(self,scentence):
            self.scentence = scentence



    def encryptor(self):
            result = []
            for letter in self.scentence:
                    l = ord(letter)+20
                    result.append(l)
            for numbers in result:
                    print(numbers,end = '')
                    print(" " , end = '')
            print(result)
    def decryptor(result):
            print(result)

            end_string = ""
            for j in result:
                    l = int(j)
                    l = l-20
                    l = chr(l)
                    end_string = end_string + l


            print("The decrypted message is below:")
            print(end_string)

f = Encrypt("helloe")
f.encryptor()
f.decryptor()

So when i run this code there is error as follows

for j in result: TypeError: 'Encrypt' object is not iterable

It would be very helpful for someone to explain the concept of SELF and OBJECT and CLASS

bashkash
  • 47
  • 7
  • 2
    Always post the full error message including stack trace. But your problem is the way you've defined your second method. All methods get passed the instance as the first argument, by convention, the name will be `self`. So in your case, `result` is passed the instance, and then you loop over it, but it isn't iterable, hence the error – juanpa.arrivillaga Nov 17 '19 at 19:54
  • And `result` itself should be returned from the `encryptor` function. Then, `f.encryptor(f.decryptor)`. – Alexander Nov 17 '19 at 20:02

1 Answers1

2

In Python, the first parameter for class methods is always self (whereas in other object-oriented languages like C++ and Java this parameter is implicit). For an explanation of why, see https://stackoverflow.com/a/2709832/4454124. (self is merely the conventional name given to the first parameter, but the name could be anything, like self, this, banana, or result)

Because you don't have the self parameter in your decryptor() method, the Python interpreter will try to interpret the parameter you do provide (result) as the self parameter, meaning it expects it to be of type Encrypt which it is not, hence the error.

As a side note, in an object-oriented program the name of the class should be a noun, and method names should be verbs -- so in your program you would have a class called "Encryptor" and methods called "encrypt" and "decrypt".

mnistic
  • 10,866
  • 2
  • 19
  • 33
  • you should really make it clear that `self` is merely the conventional name given to the first parameter, which is what will always get passed the instance upon invocation of the method on the instance. It can be whatever, though, `self`, `this`, `banana`, or `result`... – juanpa.arrivillaga Nov 17 '19 at 20:11