8.modifying member variables
1.inside the Car class,add a method drive_car() that sets self.condition to the string "used".
2.remove the call to my_car.display() and instead print only the condition of your car.
3.then drive your car by calling the drive_car() method .
4.finally,print the condition of your car again to see how its value changes.
class Car(object):
condition = "new"
def init(self,model,color,mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.model,self.color,self.mpg)
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean","silver",88)
print my_car.condition
my_car.drive_car()
print my_car.condition
my_car = Car()这行要在def下面,在上面程序出错,不能调用程序。
11.building useful classes
1.define a Point3D class inherits from object
2.inside the Point3D class,define an init() function that accepts self,x,y and z,and assigns these numbers to the member variables self.x,self.y,self.z.
3.define a repr() method that returns "(%d, %d, %d)" % (self.x,self.y,self.z).this tells python to represent this object in the following format:(x,y,z).
4.outside the class definition ,create a variable named my_point containing a new instance of Point3D with x=1,y=2,z=3.
5.finally,print my_point
class Point3D(object):
def init(self,x,y,z):
self.x = x
self.y = y
self.z = z
def repr(self):
return "(%d, %d, %d)" % (self.x,self.y,self.z)
my_point = Point3D(1,2,3)
print my_point
%d, %d
,和%之间有空格
object 是小写