Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class instance from one file in another file?

I have two files, both are in the same project (part of a web scraping framework). File1 processes items that are generated by File2. In File2 I have a function that prints out some basic stats about the processes (counts of how many items have been generated, etc). I have counts in File1 that I would like to print with the stats from File1 but am unsure of how to do that. Take a look at the example code.

FILE 1:

class Class1(object):
    def __init__(self):
        self.stats = counter("name") #This is the instance that I'd like to use in File2
        self.stats.count = 10

class counter:
    def __init__(self, name):
        self.name = name
        self.count = 0
    def __string__(self):
        message = self.name + self.count
        return message

FILE 2: (this is what I'd like to do)

from project import file1 # this import returns no error

def stats():
    print file1.Class1.stats # This is where I'm trying to get the instance created in Class1 of File2.
    #print file1.Class1.stats.count # Furthermore, it would be nice if this worked too.

ERROR:

exceptions.AttributeError: type object 'Class1' has no attribute 'stats'

I know that both files are running, thus so does the 'stats' instance of the 'counter' class, because of other methods being printed out when running the project (this is just a stripped down example. What am I doing wrong here? Is this possible to do?

like image 203
alukach Avatar asked Sep 02 '11 23:09

alukach


People also ask

How to call a class from another py file?

Importing a specific class by using the import command You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

Can you define MULTIPLE classes in one python file?

In Python there is rule of one module=one file. In Python if you restrict yourself to one class per file (which in Python is not prohibited) you may end up with large number of small files – not easy to keep track. So depending on the scenario and convenience one can have one or more classes per file in Python.


1 Answers

This is not working because you never instantiate Class1.

__init__ is called when the Class1 is instantiated so Class1.stats is set.

You have 2 options here.

  1. instantiate Class1 in file 2 somehow.
  2. declare a static method in Class1 that returns the count property.
like image 188
Jonathan Liuti Avatar answered Sep 25 '22 10:09

Jonathan Liuti