【发布时间】:2014-06-07 22:26:43
【问题描述】:
我已经完成了几个关于 Python 的教程,并且我知道如何定义类,但我不知道如何使用它们。例如,我创建了以下 file (car.py):
class Car(object):
condition = 'New'
def __init__(self,brand,model,color):
self.brand = brand
self.model = model
self.color = color
def drive(self):
self.condition = 'Used'
然后我创建另一个文件 (Mercedes.py),我想从 Car 类中创建一个对象 Mercedes:
Mercedes = Car('Mercedes', 'S Class', 'Red')
,但我得到一个错误:
NameError: name 'Car' is not defined
如果我在创建实例(汽车)的同一文件中创建实例(对象),则没有问题:
class Car(object):
condition = 'New'
def __init__(self,brand,model,color):
self.brand = brand
self.model = model
self.color = color
def drive(self):
self.condition = 'Used'
Mercedes = Car('Mercedes', 'S Class', 'Red')
print (Mercedes.color)
哪些打印:
Red
所以问题是:如何从同一个包(文件夹)中不同文件的类创建对象?
【问题讨论】:
-
你知道
condition是一个类属性,被所有实例共享吗? -
@jonrsharpe,为了每个对象分开,我应该把它重命名为self.condition?
-
是的,设置为
self.condition = 'New'inside__init__。
标签: python class object package