如何将类/模块定义传递到另一个文件中

时间:2014-11-23 01:54:29

标签: python import module conventions

我是OOP Python的初学者,我只是想知道这个:

这是 file.py

class Card():

    def __init__(self, rank, suit):
        """Initialization method"""
        self.rank = rank
        self.suit = suit

    def get_rank(self):
        """Function get_rank returns a rank (value) of the card"""
        return self.rank

当我想创建并将对象传递给函数" get_rank"在这个文件中,我可以这样做:

card1 = Card(10,"Diamond")
card1.get_rank()

但是如何创建并传递另一个文件中的对象?还有另一个名为 test_file.py 的文件,它是一个测试文件(py.test)。因此 file.py 仅用于代码, test_file.py 表示传递给 file.py 的参数(变量和对象)。在 test_file.py 中也是变量" expected_result"结果正确。然后,当我使用" py.test" (bash),它告诉我,如果结果是否正确。

我理解这个非OOP示例: 的 abs.py

def split_text(text): - code -

test_abs.py

def test():
    text = 'abcdefgh'

请帮助,感谢您的任何建议:)

1 个答案:

答案 0 :(得分:2)

test_file.py

from file import Card

...
card1 = Card(10, "Diamond")
# Do something with it

顺便说一句,不要将文件命名为file.py: file是一个内置函数。

相关问题