• 技术文章 >常见问题 >Python常见问题

    如何引入类python

    silencementsilencement2020-01-02 14:17:27原创1550

    现有自定义类(Color.py)如下,类位于路径’/Users/chuxing/python/test’下:

    class Color(object):
    
        def __init__(self, red, green, blue):
            self.red = red;
            self.green = green;
            self.blue = blue;
    
        def __str__(self):
            return '(%s,%s,%s)' %(self.red, self.green, self.blue);

    在另一个类Food.py中需要使用Color类,Food.py内容如下:

    import sys;
    sys.path.append('/Users/chuxing/python/test');
    from Color import Color;
    
    class Food(object):
    
        def __init__(self, color):
            self.color = color;
    
        def __str__(self):
            return '(%s)' %self.color;
    
    black = Color(1,2,3);
    drink = Food(black);
    print(drink);

    将Color类导入Food类的方式如下:

    import sys;sys.path.append('/Users/chuxing/python/test');
    from Color import Color;

    推荐学习《python教程》。

    专题推荐:class
    品易云
    上一篇:win8无法安装python3怎么办 下一篇:python需要数学基础吗

    相关文章推荐

    • Python之classmethod和staticmethod的区别• python抽象基类之_subclasshook_方法• python里的class怎么写• python class是什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网