python--类(面向对象)
类和实例:可将类视为创建实例的说明
__init__是一个特殊的方法,当根据类创建新实例时会被自动运行。
self:每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。以self为前缀的变量都可供类中的所有方法使用,称之为属性
1.创建类
创建一个小猫的类,这个小猫不是特定的某个小猫,是任何小猫。有名字和年龄。包含吃,跳等动作。
class Cat(): def __init__(self,name,age): self.name=name self.age=age def eat(self): #只有吃不包含其他信息,传递形参self print(self.name.title()+"is eatting now.") def jump(self): print(self.name.title() + "will jump.")
2.创建实例
my_cat=Cat('mimi',6)
3.访问属性
print("My cat'name is"+my_cat.name.title()+","+str(my_cat.age)+"岁了。") #My cat'name isMimi,6岁了。
4.调用方法
my_cat.eat() #Mimiis eatting now.
5.创建多个实例
his_cat=Cat('doggy',4) print("His cat'name is"+his_cat.name.title()+","+str(his_cat.age)+"岁了。") his_cat.jump()
#例子:创建一个名为Restaurant 的类,其方法__init__() 设置两个属性:restaurant_name 和cuisine_type 。创建一个名为describe_restaurant() 的方法和一个名为open_restaurant() 的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。
根据这个类创建一个名为restaurant 的实例,分别打印其两个属性,再调用前述两个方法。
class Restaurant(): def __init__(self,restaurant_name,cuisine_type): self.name=restaurant_name self.type= cuisine_type def describe_restaurant(self): print("this restaurant's name is" + self.name) print( "its type is" + self.type) def open_restaurant(self): print(self.name +"is opening now.") restaurant=Restaurant("louise's",'chinese food') restaurant.describe_restaurant() #this restaurant's name islouise's its type ischinese food restaurant.open_restaurant() #louise'sis opening now.
#给属性制定默认值
#类中的每个属性都必须有初始值,如果在方法__init__中制定初始值,就无需包含形参
class Car(): def __init__(self,make,model,year): self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): # print(str(self.make)+" "+self.model+' ' + self.year) long_name=str(self.make)+" "+self.model+' ' + str(self.year) return long_name def read_odometer(self): print("this car has" + str(self.odometer_reading)+"miles on it.") my_car=Car('bmw','x6',2023) # my_car.get_descriptive_name() print(my_car.get_descriptive_name()) #bmw x6 2023 my_car.read_odometer() #this car has0miles on it.
#修改属性的值
#直接修改
my_car.odometer_reading = 22 my_car.read_odometer() #this car has22miles on it.

浙公网安备 33010602011771号