частные переменные, записанные в текстовый файл - PullRequest
0 голосов
/ 11 декабря 2018

Ниже перечислены основные функции и определенные функции, однако я получаю сообщение об ошибке, что у меня нет атрибута «output_info» для записи текстового файла.Когда я пытаюсь использовать следующий код, он дает мне attribute_error.Я не могу скопировать информацию в нужный текстовый файл.Я не знаю, как вызвать эту частную переменную экземпляра в текстовый файл и почему она дает мне ошибку, что у меня нет атрибута, который был определен.Пожалуйста, помогите !!

Определение функций (переменные экземпляра должны быть частными): класс Customer:

def __init__(self,email="",last="",first="",age=0,pswd="",card="",sec=""):
    self.__email=email
    self.__last=last
    self.__first=first
    self.__age=age
    self.__pswd=pswd
    self.__card=card
    self.__sec=sec

def input_age(self):
    correct=True
    while correct == True:
        try:
            input_age=int(input("Please enter age"))
            if input_age < 0:
                print("You have entered an invalid age, age cannot be negative")
            else:
                correct=False
                self.age=input_age
        except ValueError:
            print("You have entered an invalid age, age must be a positive whole number")


def input_password(self):

    import re
    correct=True
    while correct==True :
        try:
            password=input("Please enter a password 8-12 characters with at least one upper case letter, one lower case letter and one number")
            if re.search('[A-Z]',password) is None:
                print("Password must contain at least one capital letter")
            elif re.search('[0-9]',password) is None:
                print("Password must contain at least one number.")
            elif re.search('[a-z]',password) is None:
                print("Password must contain at least one lowercase letter.")
            elif len(password)<8:
                print("Password is too short, must contain at least 8 letters")
            elif len(password)>12:
                print("Password is too long, must contain at least 8 but no more than 12 charachters")
            else:
                self.pswd=password
                correct=False
        except ValueError:
            print("Please reenter password")

def input_card_number(self):
    import re
    correct=True
    while correct==True:
        try:
            card=input("Please enter your 16 digit card number")
            if card.isdigit() == True:
                if len(card) < 16:
                    print("Invalid card number, you may have missed a digit")
                elif len(card) > 16:
                    print("Invalid card number, you may have accidentally hit a number twice.")
                else:
                    self.card=card
                    correct=False
            else:
                print("Invalid card entry, no letters in card number")
        except ValueError:
            print("Invalid card number, try again")

def input_security_code(self):
    correct=True
    while correct == True:
        try:
            sec= input("Please enter the 3 digit security code")
            if sec.isdigit()==True:
                if len(sec) < 3:
                    print("Invalid Security Code, You may have missed a digit")
                elif len(sec) > 3:
                    print("Invalid Security Code, You may have accidentally hit a digit twice")
                else:
                    self.sec=sec
                    correct=False
            else:
                print("Inv
def getInfo(self):
    return self.first,self.last,self.age,self.email,self.pswd,self.card,self.sec

def output_info(self):
    self.getInfo()
    info=(self.first," ", self.last," ", str(self.age)," ", self.email," ",self.pswd," ",self.card, " ",self.sec,"\n")
    output_file = open('customers.txt', 'a')
    output_file.write(info)
    output_file.close()

1 Ответ

0 голосов
/ 11 декабря 2018

Закрытые переменные не изменяются внутри класса, поэтому, если вы хотите получить к ним доступ, вам необходимо включить префикс dunder ("__").Например:

class Customer:
    def __init__(self, email="", last="", first="", age=0, pswd="", card="",
                 sec=""):
        self.__email = email
        self.__last = last
        self.__first = first
        self.__age = age 
        self.__pswd = pswd
        self.__card = card
        self.__sec = sec 

    def output_info(self):
        output = " ".join((self.__first, self.__last, self.__age,
                           self.__email, self.__pswd, self.__card,
                           self.__sec))
        with open('customers.txt', 'a') as fhandle:
            fhandle.write(output)

Могу ли я предложить вам использовать IDE, которая автоматически заполняет доступные вам атрибуты / методы, пока вы не почувствуете, как они работают.

...