class Dog(): def __init__(self,name,age): self.name = name self.age = age def sit(self): print(self.name.title()+"is now setting") def rollOver(self): print(self.name + "is roll over") #引用实例 myDog = Dog("小怪",4) print("my dog is "+str(myDog.age)+" age!") #my dog is 4 age! myDog.sit() #小怪is now setting myDog.rollOver() #小怪is roll over
其中的_init_(self)是必须的,相当于C++的构造函数,self是指向实例本身的引用,相当于C++类的this指针
#给属性指定默认值 class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odomete_reading = 0 #指定默认值 def get_descriptive_name(self): long_name = str(self.year) + " " + self.model + " " + self.model return long_name.title() def read_odometer(self): print("the car has " + str(self.odomete_reading) + " mlies on it !") #实例化一个car my_new_car = Car('audi','a4',1998) car_info = my_new_car.get_descriptive_name() print(car_info) #1998 A4 A4 my_new_car.read_odometer() #the car has 0 mlies on it !
修改属性的值有三种方法:直接通过实例进行修改;通过方法进行设置;通过方法增加特定的值
#方法一
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odomete_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + " " + self.make + " " +self.model return long_name def read_odometer(self): print("the car has " + str(self.odomete_reading) + " mlies!") my_new_car = Car('audi','a4',1996) my_new_car.odomete_reading = 10000 long_name = my_new_car.get_descriptive_name() print(long_name) my_new_car.read_odometer() #直接在实例中修改属性的值
#方法二
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odomete_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + " " + self.make + " " +self.model return long_name def read_odometer(self): print("the car has " + str(self.odomete_reading) + " mlies!") def update_odometer(self,mlies): self.odomete_reading = mlies my_new_car = Car('audi','a4',1996) my_new_car.update_odometer(9202) #通过调用函数update_odometer来更新类内的属性 long_name = my_new_car.get_descriptive_name() print(long_name) my_new_car.read_odometer() #the car has 9202 mlies!
#方法三
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odomete_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + " " + self.make + " " +self.model return long_name def read_odometer(self): print("the car has " + str(self.odomete_reading) + " mlies!") def update_odometer(self,mlies): #修改参数odomete_reading的值 self.odomete_reading = mlies def increment_odometer(self,mlies): #通过内部的方法来使的内部数据增加 self.odomete_reading += mlies my_new_car = Car('audi','a4',1996) my_new_car.update_odometer(9202) #通过调用函数update_odometer来更新类内的属性 my_new_car.read_odometer() #the car has 9202 mlies! long_name = my_new_car.get_descriptive_name() print(long_name) my_new_car.increment_odometer(20) my_new_car.read_odometer() #the car has 9222 mlies!