Python Forum

Full Version: problem with "hiding" object
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is code that's supposed to generate a cipher once, then prevent the cipher from being altered or viewed, but the code doesn't work. What's wrong with it?

from cryptography.fernet import Fernet


class Cipher:

    def __init__(self, value=None):
        self.cipher = Fernet(Fernet.generate_key())

    @property
    def cipher(self):
        return self.__cipher

    @cipher.setter
    def cipher(self, value=None):
        if not self.__cipher:
            self.__init__()
        else:
            raise ValueError("Cipher may not be altered.")

    def __repr__(self):
        return "Cipher may not be viewed."
(Jan-16-2018, 07:30 PM)league55 Wrote: [ -> ]the code doesn't work.
how exactly doesn't work? Show us how you run it, i.e. how you instantiate object of class Cipher.
If you get ant error, post the full traceback in error tags.
Here is the instantiation:

cipher = Cipher()
And here's the error message:

Output:
Traceback (most recent call last): File "C:\Users\leagu\pythonprojects\costcontrol\classes\keyclass.py", line 25, in <module> cipher = Cipher(data) File "C:\Users\leagu\pythonprojects\costcontrol\classes\keyclass.py", line 7, in __init__ self.cipher = value File "C:\Users\leagu\pythonprojects\costcontrol\classes\keyclass.py", line 15, in cipher if self.cipher != None: File "C:\Users\leagu\pythonprojects\costcontrol\classes\keyclass.py", line 11, in cipher return self.__cipher AttributeError: 'Cipher' object has no attribute '_Cipher__cipher'
Why do you name the attribute and the methods with the same name?
I found out from other sources that, in Python, you can't protect an object's attributes, so what I'm trying to do won't work. Thanks for your time.