为每个类的实例做一些事情

时间:2014-07-31 13:48:23

标签: python object

好的,所以在这段代码中:

paint():
    print("So you want to paint your car?")
    color = input("What color will it be? ")
    carx.color = color                          #x = a car

class car:
    def __init__(self, tires, color, age):
        self.tires = tires
        self.color = color
        self.age = age

car1 = car(3, "Red", "1996")
car2 = car(4, "Blue", "2001")
car3 = car(4, "Black", "2006")

paint()

我想做的是画三辆车。如你所见,在第4行,我写了carx。我意识到这不是怎么做的,而是无论如何。我的意思是,这就是我要问的问题,我该怎么写?

另外,我意识到这可以通过在paint()中返回一个值来完成,但是也可以这样做吗?

编辑:删除了一些不必要的代码。

3 个答案:

答案 0 :(得分:2)

这可以通过稍微改变一下类结构来实现:

class Car: # class names are generally capitalized so that you can tell they're not local variable names.
    def __init__(self, tires, color, age):
        self.tires = tires
        self.color = color
        self.age = age

    def paint(self): # We make paint() a method of car
        print("So you want to paint your car?")
        color = input("What color will it be? ")
        self.color = color   

由于paint现在是car的方法,我们现在可以执行以下操作:

# First build a list of your cars
car1 = Car(3, "Red", "1996"),
car2 = Car(4, "Blue", "2001"),
car3 = Car(4, "Black", "2006")
cars = [car1, car2, car3]

# Then loop over it calling paint()
for car in cars:
    car.paint()

# I can can also still access them directly
car1.paint()

# And since Python uses references for everything, the version in the list will be updated as well
cars[0].color == car1.color # will be True

但是,如果您希望paint()更具通用性并适用于许多可以 paintable 并且始终具有名为color的属性,那么它将是甚至更好地建立一个基类:

class Paintable(object):
    def __init__(self, color):
        self.color = color

    def paint(self):
        print('So you want to paint your {}?'.format(type(self).__name__)) # this will replace 'car' in your original print with whatever the class name  of the Paintable is
        self.color = input('What color will it be?')


# Now we make car inherit Paintable
class Car(Paintable):
    def __init__(self, tires, color, age):
        super(Car, self).__init__(color) # this sets the color via Paintable's constructor
        self.tires = tires
        self.age = age


 # And from here the rest is the same

这使您可以根据需要轻松地将新事物定义为“可绘制”。

如果您要问如何调用单个方法并将所有实例的color值更新为相同的值,那么这是一个不同的问题,我会相应地更新。

答案 1 :(得分:1)

没有"所有汽车"的概念。在Python的类型系统中。您的程序基本上有一个指向对象的有向图:

main module
  "car"  --------------------------------------> \
  "car1" --> Car(3, "Red", "1996"),   class --->  } -> class "Car"
  "car2" --> Car(4, "Blue", "2001"),  class ---> /
  "car3" --> Car(4, "Black", "2006"), class --->/

班级"汽车"不知道任何个人" Car"例如,他们也不知道彼此。跟踪组的传统方法是将它们存储在容器中,例如列表:

mycars = [car1, car2, car3]
for car in mycars:
  car.color = "octarine"

虽然被广泛认为是不卫生的,但也有可能检查你自己的命名空间以找到汽车:

for name,obj in locals().items():
  if isinstance(obj,car):
    print("Found a car named %s, painted %s"%(name,obj.color))

但是请注意,这会两次找到您的一辆车,因为obj也是一个本地变量。

另一种方法是让班级自动维护所有汽车的列表,但这需要另一个有趣的黑客来阻止永恒的汽车:weak references

import weakref
class car:
    all=weakref.WeakSet()
    def __init__(self, tires, color, age):
        self.tires = tires
        self.color = color
        self.age = age
        self.all.add(self)
def paintallcars(color):
    for carinstance in car.all:
        carinstance.color = color

通常,传统列表更有意义,因为您在一个或多个上下文中跟踪任意数量的汽车。

答案 2 :(得分:0)

如果你用一个非特定的变量定义你的类,如下所示:

class car:
    color = 'red'
    def __init__(self):
     ...

然后所有汽车共享相同的属性

car1 = car()
car2 = car()
car.color = 'yellow'

>>> print car1.color
yellow
>>> print car2.color
yellow

这是colorself.color之间的差异。 self.color特定于每个类,color类似于C ++中的静态类变量,所有汽车对象都看到同一个。