如何使用python创建一个对象,该对象将另一个对象作为参数

时间:2017-05-04 10:59:17

标签: python

我想创建自己的日志记录类:它将一些数据写入文本文件。

为此,我创建了一个类mylog.py

我希望能够创建mylog.py类的实例对象,并将实例对象作为参数传递给我编写的其他类。

然而,当我尝试使用自我符号访问mylog对象而不使用自我符号时,我遇到了问题。

问题是当我在启动类中引用mylog对象并使用self.log = logger时,这不能使用mylog类的方法,如self.log.write(),也不能设置logobj没有自我的变量,并将其传递给。

我的mylog.py类

import datetime
import os

class logtextfile(object):


    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "{} ".format(self.__class__.__name__)

    def write(self,**kwargs):
        """Writes a log message to a user specified file which indicates the action takes and if it was successful"""
        self.file = kwargs.get('file',"log.txt")
        self.loglevel = kwargs.get('loglevel',"critical")
        self.logmessage = kwargs.get('logmessage',"error")
        self.success = kwargs.get('success',False)
        self.class_name = kwargs.get('class',str("{}".format(self.__class__.__name__)))
        self.output = ", ".join([str(datetime.datetime.now().replace(second=0,microsecond=0)),self.class_name,str(self.logmessage),str(self.success),str("\n")])

        for key, value in kwargs.items():
            setattr(self,key,value)

        f = open(str(self.file),"a")
        f.write(self.output)
        f.close()

    def now(self, filename, openas, data):
        """Creates a log file with todays date and time"""
        fmt='%Y-%m-%d-%H-%M-%S_{fname}'
        fn = datetime.datetime.now().strftime(fmt).format(fname=filename)
        f = open(str(fn),openas)
        f.write(data + "\n")
        f.close()

我的初创班级

import pandas as pd
import numpy as np
from pandas_datareader import data as web
import datetime
import requests
import lxml
from IPython.display import clear_output
import time
import timeit
from bs4 import BeautifulSoup
import re
import os
import sqlite3
from sqlalchemy import create_engine # database connection
from zenlog import log

class company(object):

    def __init__(self, name, logobj):
        self.name = name
        logger = logobj

    def __str__(self):
        return "{} ".format(self.__class__.__name__)

    def listed(self):
        try:
            #all companies on asx downloaded from asx website csv
            self.function_name = str("{}".format(self.__class__.__name__))
            df = pd.read_csv('http://asx.com.au/asx/research/ASXListedCompanies.csv', skiprows=1)
            df.columns = ["company","asx_code","industry"]
            df["yahoo_code"] = df["asx_code"]+".AX"
            message = "succesfully downloaded ASXListedCompanies.csv"
            logger.write(file="asx_module_log.txt",logmessage=message,success=True)
            return df
        except:
            message = "ASXListedCompanies.csv could not be retrieved, the website is unavailable"
            try:
                logger.write(file="asx_module_log.txt",logmessage=message)
            except:
                log.critical(message)

    def valid(self):
        try:
            df = self.listed()
            return df[(df["industry"]!= "Not Applic") & (df["industry"]!="Class Pend")]
        except:
            message = "Could not retrieve listed companies object with pandas dataframe"
            try:
                logfile.write(file="asx_module_log.txt",logmessage=message)
            except:
                log.critical(message)

    def invalid(self):
        try:
            df = self.listed()
            return df[(df["industry"]=="Not Applic") | (df["industry"]=="Class Pend")]
        except:
            message = "Could not retrieve listed companies object with pandas dataframe"
            try:
                logfile.write(file="asx_module_log.txt",logmessage=message)
            except:
                log.critical(message)

我的代码创建一个mylog实例并将其传递给启动类,以便它可以登录到文本文件。

import mylog
import startup

logger = mylog.logtextfile(name="mylogfile")

c = startup.company(name="mycompany",logobj=logger)
df = c.invalid()
df.head()

2 个答案:

答案 0 :(得分:0)

简单地:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

class A(object):

    def __init__(self, x=None):
        self.x = x


class B(object):

    def __init__(self, a):
        if (isinstance(a, A)):
            self.x = a.x
        else:
            self.x = 0


if __name__ == "__main__":
    a = A(10)
    b = B(a)

答案 1 :(得分:0)

我无法测试你的company课程:我没有大多数第三方模块。但是,拥有“裸”except条款通常是一个坏主意。使用命名异常,否则你可能会捕捉到你不期望的东西。

无论如何,这是一个在另一个类的实例中使用你的记录器的简短演示。

import datetime

class LogTextfile(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "{} ".format(self.__class__.__name__)

    def write(self, **kwargs):
        """ Writes a log message to a user specified file which
            indicates the action takes and if it was successful
        """
        self.file = kwargs.get('file', "log.txt")
        self.loglevel = kwargs.get('loglevel', "critical")
        self.logmessage = kwargs.get('logmessage', "error")
        self.success = kwargs.get('success', False)
        self.class_name = kwargs.get('class', str("{}".format(self.__class__.__name__)))
        self.output = ", ".join([str(datetime.datetime.now().replace(second=0, microsecond=0)),
            self.class_name, str(self.logmessage), str(self.success), str("\n")])

        for key, value in kwargs.items():
            setattr(self, key, value)

        f = open(str(self.file), "a")
        f.write(self.output)
        f.close()

    def now(self, filename, openas, data):
        """Creates a log file with todays date and time"""
        fmt = '%Y-%m-%d-%H-%M-%S_{fname}'
        fn = datetime.datetime.now().strftime(fmt).format(fname=filename)
        f = open(str(fn), openas)
        f.write(data + "\n")
        f.close()

class Test(object):
    def __init__(self, logger):
        self.logger = logger

    def logtest(self, message):
        self.logger.write(logmessage=message)


logger = LogTextfile(name="mylogfile")
logger.write(logmessage='This is a test')

t = Test(logger)
t.logtest('Message from Test')

“log.txt”的内容

2017-05-04 22:40:00, LogTextfile, This is a test, False, 
2017-05-04 22:40:00, LogTextfile, Message from Test, False,