从文本文件分配设置/获取方法

时间:2018-11-12 19:05:17

标签: python

我刚接触Python(大约5个月),请原谅我的无知。我的任务是创建一个程序来做一些事情。

首先,我有一个文本文件,其信​​息存储如下:

姓名,街道,城市所在州的邮政编码,生日,宠物。

第二,我的指示包括:

  • 读取文本文件并确定年龄,并根据该年龄确定折扣。例如,如果年龄为18 -25岁,则可享受5%的折扣。
  • 与供应商匹配宠物偏好

我正在为每个属性使用类。我有一个关于班级信息的单独文件,如下所示。我为列出的每个属性设置/获取方法。

来自information.py

class GetInfo:
    def __init__(self,name,street,city,state,zipcode,birthday,pet):
        self.__name = name

    def set_name(self,name):
        self.__name = name

    def get_name(self):
        return self.__name

最后,我必须为每个人写一封信。我不知道如何从本质上保持数据分开以便每个人写一封信。我将使用.write(str)方法编写每一行。到目前为止,这是我的主要程序:

import information
import os
import time
CURRENT_YEAR = 2018

def main():
    customerInfo = information.GetInfo(name,street,city,state,zipcode,birthday,pet)
    tempFile = open('temp.txt','w')
    with open('c.TXT') as customerList:
    lines = customerList.readlines()
    for line in lines:
        tempFile.write( str(GetInfo.name) + '\n')
    tempFile.close()
main()

对于供应商列表,我将有一个字典,例如:

vendors = {"Cat:CatCity"}

下一步我很困惑,同时在尝试运行程序时也收到此错误:

"main.py", line 10, in main customerInfo = information.GetInfo(name,street,city,state,zipcode,birthday,pet)
NameError: name 'name' is not defined

1 个答案:

答案 0 :(得分:-1)

尝试这个课程:

$nav =array("home"=>"home.php",
    "flight"=>"flight-detail.php",
    "order"=>"order-flight.php",
    "testimonial"=>"add-testimonial.php");

if(isset($_GET['page']) && in_array($_GET['page'], array_keys($nav))){
    header('Location: ' . $nav[$_GET['page']]);
}else{
    header('Location:index.php');
}
exit();

您不需要使用getter和setter。在python中,您可以访问没有它们的对象的所有属性。另请参阅:Using @property versus getters and setters

您代码中的实际问题是线路

class GetInfo:
    def __init__(self,name,street,city,state,zipcode,birthday,pet):
        self.inner_name = name

    @property
    def get_name(self):
        return self.inner_name

    @name.setter
    def set_name(self, name):
        self.inner_name = name

对象tempFile.write( str(GetInfo.name) + '\n') 不是类的实例,而是类本身。并且该类没有属性GetInfo。您可能的意思是:

name