سؤال

أقوم بتشغيل Python 2.6.1 على Windows XP SP3. IDE الخاص بي هو Pycharm 1.0-Beta 2 Build Py-96.1055.

أقوم بتخزين ملفات .py في دليل يسمى "SRC" ؛ لديها __init__.py ملف فارغ باستثناء "__author__"سمة في الأعلى.

يسمى واحد منهم matrix.py:

#!/usr/bin/env python
"""
"Core Python Programming" chapter 6.
A simple Matrix class that allows addition and multiplication
"""
__author__ = 'Michael'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"

class Matrix(object):
    """
    exercise 6.16: MxN matrix addition and multiplication
    """
    def __init__(self, rows, cols, values = []):
        self.rows = rows
        self.cols = cols
        self.matrix = values

    def show(self):
        """ display matrix"""
        print '['
        for i in range(0, self.rows):
            print '(',
            for j in range(0, self.cols-1):
                print self.matrix[i][j], ',',
            print self.matrix[i][self.cols-1], ')'
        print ']'

    def get(self, row, col):
        return self.matrix[row][col]

    def set(self, row, col, value):
        self.matrix[row][col] = value

    def rows(self):
        return self.rows

    def cols(self):
        return self.cols

    def add(self, other):
        result = []
        for i in range(0, self.rows):
            row = []
            for j in range(0, self.cols):
                row.append(self.matrix[i][j] + other.get(i, j))
            result.append(row)
        return Matrix(self.rows, self.cols, result)

    def mul(self, other):
        result = []
        for i in range(0, self.rows):
            row = []
            for j in range(0, other.cols):
                sum = 0
                for k in range(0, self.cols):
                    sum += self.matrix[i][k]*other.get(k,j)
                row.append(sum)
            result.append(row)
        return Matrix(self.rows, other.cols, result)

    def __cmp__(self, other):
        """
        deep equals between two matricies
        first check rows, then cols, then values
        """
        if self.rows != other.rows:
            return self.rows.cmp(other.rows)
        if self.cols != other.cols:
            return self.cols.cmp(other.cols)
        for i in range(0, self.rows):
            for j in range(0, self.cols):
                if self.matrix[i][j] != other.get(i,j):
                    return self.matrix[i][j] == (other.get(i,j))
        return True # if you get here, it means size and values are equal



if __name__ == '__main__':
    a = Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    b = Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
    c = Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])
    a.show()
    b.show()
    c.show()
    a.add(b).show()
    a.mul(c).show()

لقد قمت بإنشاء دليل جديد يسمى "اختبار" يحتوي أيضًا على ملف __init__.py ملف فارغ باستثناء "__author__"سمة في الأعلى. لقد قمت بإنشاء matrixtest.py إلى وحدة مصفوفة بلدي:

#!/usr/bin/env python
"""
Unit test case for Matrix class
See http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting for Python coding guidelines
"""

import unittest #use my unittestfp instead for floating point
from src import Matrix # Matrix class to be tested

__author__ = 'Michael'
__credits__ = []
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Michael"
__status__ = "Development"

class MatrixTest(unittest.TestCase):
    """Unit tests for Matrix class"""
    def setUp(self):
        self.a = Matrix.Matrix(3, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        self.b = Matrix.Matrix(3, 3, [[6, 5, 4], [1, 1, 1], [2, 1, 0]])
        self.c = Matrix.Matrix(3, 3, [[2, 0, 0], [0, 2, 0], [0, 0, 2]])

    def testAdd(self):
        expected = Matrix.Matrix(3, 3, [[7, 7, 7], [5, 6, 7], [9, 9, 9]])    # need to learn how to write equals for Matrix
        self.a.add(self.b)
        assert self.a == expected

if __name__ == '__main__':    #run tests if called from command-line
    suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
    unittest.TextTestRunner(verbosity=2).run(suite)

ومع ذلك ، عندما أحاول تشغيل مصفوفي ، أحصل على هذا الخطأ:

C:\Tools\Python-2.6.1\python.exe "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py"
Traceback (most recent call last):
  File "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/test/MatrixTest.py", line 8, in <module>
    from src import Matrix # Matrix class to be tested
ImportError: No module named src

Process finished with exit code 1

كل ما قرأته يخبرني أن امتلاك فيه.py في جميع الدلائل يجب أن تعتني بهذا.

إذا تمكن شخص ما من الإشارة إلى ما فاتني ، فأنا أقدر ذلك كثيرًا.

أود أيضًا المشورة بشأن أفضل طريقة لتطوير وصيانة فصول اختبار المصدر والوحدة. أفكر في هذا بالطريقة التي أفعلها عادة عندما أكتب جافا: /SRC و /اختبار الدلائل ، مع هياكل حزمة متطابقة تحتها. هل هذا التفكير "البيثوني" ، أم يجب أن أفكر في مخطط تنظيم آخر؟

تحديث:

بفضل أولئك الذين أجابوا ، إليك الحل الذي نجح بالنسبة لي:

  1. تغيير الاستيراد إلى from src import Matrix # Matrix class to be tested
  2. يضيف sys.path كمتغير للبيئة في تكوين غير المألوف ، مع ./SRC و.
  3. تغيير الإعلانات في matrixtest.py كما هو موضح.
هل كانت مفيدة؟

المحلول

هذا تخمين قليلاً ، لكنني أعتقد أنك بحاجة إلى ذلكتغيير Pythonpath الخاص بك متغير البيئة لتشمل SRC وأدلة الاختبار.

تشغيل البرامج في src قد يكون الدليل يعمل ، لأن Python يقوم تلقائيًا بإدراج دليل البرنامج النصي الذي يتم تشغيله حاليًا sys.path. لذا استيراد الوحدات في src كان من شأنه أن يعمل طالما أنك تنفذ أيضًا برنامج نصي يتواجد فيه src.

ولكن الآن بعد أن قمت بتشغيل برنامج نصي من test, ، ال test تتم إضافة الدليل تلقائيًا إلى sys.path, ، في حين src ليس.

يتم إضافة جميع الدلائل المدرجة في Pythonpath sys.path, وبحث بيثون sys.path للعثور على وحدات.

أيضا ، إذا قلت

from src import Matrix

ومن بعد Matrix سوف تشير إلى الحزمة ، وتحتاج إلى القول Matrix.Matrix للوصول إلى الفصل.

نصائح أخرى

بخصوص أفضل الممارسات ، pycurl يستخدم tests الدليل في نفس مستوى رمز المصدر الرئيسي. من ناحية أخرى مثل مشاريع مثل ملتوية أو Sorl-thumbnail إستخدم test(s) الدليل الفرعي تحت رمز المصدر الرئيسي.

تم الإجابة بالفعل على النصف الآخر من السؤال ~ unutbu.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top