Composition question - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Composition question (/thread-23587.html) |
Composition question - kerzol81 - Jan-07-2020 Hi, I'm testing composition, and I don't understand the output in the log file. Here is the script: import os import time import logging import datetime class Logger: logging.basicConfig(filename=datetime.datetime.today().strftime("%Y_%m_%d.log"), format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) @staticmethod def log2file(message): logging.info(message) class Folder: _path = '' _files = [] def __init__(self, path): if not os.path.exists(path): message = "folder does not exist" raise TypeError(message) self.path = path class Source: def __init__(self, path): self.path = Folder(path) Logger.log2file("{} as source folder added".format(self.path)) class Destination: def __init__(self, path): self.path = Folder(path) Logger.log2file("{} as source folder added".format(self.path)) class XLSBackup: pass s = Source('/home/kz/a')The output in the log file is like this: 2020-01-07 10:55:56 <__main__.Folder object at 0x7f4af2ff9390> as source folder added But I expected this: 2020-01-07 10:55:56 /home/kz/a as source folder added RE: Composition question - buran - Jan-07-2020 Source.path is instance of Folder class.Folder class has no __repr__ or __str__ methods defined.Read https://docs.python.org/3/reference/datamodel.html#object.__repr__ https://docs.python.org/3/reference/datamodel.html#object.__str__ define Folder.__str__ method or as alternative use Logger.log2file("{} as source folder added".format(self.path.path))
RE: Composition question - buran - Jan-07-2020 Just to note that defining THAT much classes is not necessary, e.g. Source and Destination classes are virtually the same and almost the same as Folder RE: Composition question - kerzol81 - Jan-07-2020 Hi, thanks, I implemented __str__, and now it works lik a charm. class Folder: _path = '' _files = [] def __init__(self, path): if not os.path.exists(path): message = "folder does not exist" raise TypeError(message) self.path = path def __str__(self): return self.path (Jan-07-2020, 11:06 AM)buran Wrote: Just to note that defining THAT much classes is not necessary, e.g. Source and Destination classes are virtually the same and almost the same as Folder I know that, but it's just a composition testing. In the end there wont be 3 classes. |