Run an instance of a class from one file in another file?

I have two files, both are in the same project (part of the structure of web clips). File1 processes items created using File2. In File2, I have a function that displays some basic statistics about processes (the number of attempts to create, etc.). I have an account in File1 that I would like to print using statistics from File1, but I'm not sure how to do this. Take a look at the sample 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 would 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, an instance of the "stats" of the "counter" class, due to the fact that other methods are printed when the project starts (this is just a stripped-down example. Wrong? Is it possible to do this?

+5
3

, Class1.

__init__ Class1, Class1.stats .

2 .

  • Class1 2 -.
  • Class1, count.
+6

File1 1 .

class Class1(object):
    def __init__(self):
        self.stats = counter()
        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

class_instance = Class1()

2 :

from project import file1

def stats():
    print file1.class_instance.stats
+2

. " , , " stats "" counter "- stats counter. , , , , .

class Counter(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Counter.count += 1
        self.id = Counter.count

    def __repr__(self):
        return '<Counter: %s (%d of %d)>' % (
            self.name, self.id, Counter.count)

, ,

>>> foo = Counter('Foo')
>>> print foo
<Counter: Foo (1 of 1)>
>>> bar = Counter('Bar')
>>> print bar
<Counter: Bar (2 of 2)>
>>> print foo
<Counter: Foo (1 of 2)>
>>>

Please note that the second time you print fooupdated the counter, but it idremains the same because it countis an attribute of the class, but idis an attribute of the object, therefore (with this code) the creation bardoes not affect idof foo, but increases it Counter.count.

+1
source

All Articles