现有自定义类(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教程》。