让Python每次都创建一个新实例

时间:2016-05-10 16:33:40

标签: python oop instance

我有一个类来生成数据:

class dataGen():

        #class to generate data.

        def firstName():
                firstName = 'Storm' + str(timeGen.timeGen())
                return firstName

        def lastName():
                lastName = 'Trooper' + str(timeGen.timeGen())
                return lastName 

        def randString():
                rint = random.randint(1,20)
                r4ndString = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(rint))
                return r4ndString

        def email():
                EmailA = dataGen.randString() 
                EmailB = dataGen.randString()
                items = ['.com','.net','.org']
                tld = random.choice(items) 
                return str(EmailA) + '@' + str(EmailB) + str(tld)

        def empid(size=20, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
                return ''.join(random.choice(chars) for _ in range(size))   

        def ssnGen():
                ssnGenD = random.randint(100000000,999999999)
                return ssnGenD

制作SQL调用的类:

class sqlConn():

        #Class to handle all SQL connections

        def realEmail(cEmail):
                cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=Dev1SQL1;DATABASE=TimeCurrent;Trusted_Connection=yes')
                cursor = cnxn.cursor()
                sql = 'exec tbl.usp_Lookup_Email "%s"' % cEmail
                cursor.execute(sql)
                data = cursor.fetchall()
                return(data)

        def realEmpID(cEmpID):
                cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=Dev1SQL1;DATABASE=TimeCurrent;Trusted_Connection=yes')
                cursor = cnxn.cursor()
                sql = 'exec tbl.usp_Lookup_EmplID "%s"' % cEmpID
                cursor.execute(sql)
                data = cursor.fetchall()
                return(data)                

        def realEmpName(cFName, cLName):
                cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=Dev1SQL1;DATABASE=TimeCurrent;Trusted_Connection=yes')
                cursor = cnxn.cursor()
                value = (cFName, cLName)
                sql = 'exec tbl.usp_Lookup_Name "%s", "%s"' % value                
                cursor.execute(sql)
                data = cursor.fetchall()
                return(data)

        def realSSN(cSSN):
                cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=Dev1SQL1;DATABASE=TimeCurrent;Trusted_Connection=yes')
                cursor = cnxn.cursor()
                sql = ' exec tbl.usp_Lookup_SSN "%s"' % cSSN
                cursor.execute(sql)
                data = cursor.fetchall()
                return(data)

...我有一个基于我的SQL查询结果调用它的类。

def deID(HOLDERLIST):
        #Takes in the holderList from holderClass, checks aganst the database to see if the fakeFeild for each of the values has data,
        #If the feild does not return none, it uses that data.  If it is none, then it generates new data.
        for item in HOLDERLIST:
                for idx, lis in enumerate(item):                        
                        if idx == 0:
                                fName = item[0]
                                lName = item[1]
                                name = sqlConn.realEmpName(fName, lName)
                                if name == None:
                                        item[0] = dataGen.firstName()
                                        item[1] = dataGen.lastName()

                                else:
                                        item[0] = name[0][0]
                                        item[1] = name[0][1]

                        elif idx == 2:
                                SSN = sqlConn.realSSN(item[idx])
                                if SSN == None:
                                        item[idx] = dataGen.ssnGen()                                        
                                else:
                                        item[idx] = SSN                                        

                        elif idx == 3:
                                email = sqlConn.realEmail(item[idx])
                                if email == None:
                                        item[idx] = dataGen.email()
                                else:
                                        item[idx] = email                                       


        print('Holderlist deID')          
        return(HOLDERLIST)

我的主循环

def main():

        datagenInstance = dataGen()
        SQLConnInstance = sqlConn()  
        CLIENT, filename, FILESTRUCT = selectFile()
        PARSED = parse(filename)
        HOLDERLIST = holderClass(PARSED, FILESTRUCT)
        deIDedData = deID(HOLDERLIST)
        deIDedFile = merge(PARSED, deIDedData, FILESTRUCT)
        fileExport(filename, deIDedFile)

if __name__ == '__main__':

    main()

HOLDERLIST只是一个CSV文件,被解析为4个字符串的列表。我遇到的问题是SQL连接类和dataGen类每次都没有进行新的调用。每次循环运行时,它应该创建上述两个类的新实例。我知道在c#和c ++之类的语言中,我可以在调用的前面添加新内容以强制语言在每次调用时创建一个新实例。我已经阅读了有关在python中使用 new 等内容的文献,但这似乎放在了类声明中,我并不太了解python的类装饰。

1 个答案:

答案 0 :(得分:2)

您似乎对Python中的类不太熟悉。您已经创建了两个只包含类方法而没有实例属性的类。要将dataGen类更新为基于实例,可以使用以下内容:

class DataGen(object):
    def __init__(self):
        self.first_name = 'Storm' + str(timeGen.timeGen())
        self.last_name = 'Trooper' + str(timeGen.timeGen())
        self.email = DataGen.rand_email()
        self.empid = DataGen.rand_empid()
        self.ssn = DataGen.rand_ssn()

    @staticmethod
    def rand_string():
        r_int = random.randint(1,20)
        r_string = ''.join(random.choice(string.ascii_uppercase + 
                         string.ascii_lowercase + string.digits) 
                    for _ in range(r_int))
        return r_string

    @staticmethod
    def rand_email():
        email_a = DataGen.rand_string() 
        email_b = DataGen.rand_string()
        items = ['.com','.net','.org']
        tld = random.choice(items) 
        return str(email_a) + '@' + str(email_b) + str(tld)

    @staticmethod
    def rand_empid(size=20, chars=string.ascii_uppercase + 
                                string.ascii_lowercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))

    @staticmethod
    def rand_ssn():
        ssn = random.randint(100000000,999999999)
        return ssn

创建类的实例时,将调用__init__函数并用于实例化类(通常表示设置实例属性)。所有实例方法都隐式传递参数self,它是类的实例。装饰器staticmethod会覆盖此行为,并且在调用这些方法时,不会隐式传递任何参数。创建实例并访问其属性是直截了当的。

instance = DataGen()

print(instance.first_name) # Storm8
print(instance.last_name) # Trooper6
print(instance.email) # xOy37zF@bR68DdLr36mq.net
print(instance.empid) # JhPGpnwUQlm9tCaWbW3F
print(instance.ssn) # 370469583

但是,当您在主循环中创建datagenInstance时,它不会在任何地方使用。您需要将其传递给相关功能。由于您可能需要重新构建大量代码,因此很难提供比此更多的指导。 This link可以帮助您更好地解释课程。