要在Python中导入一个类,需要使用import
关键字。
详细去看下面的代码
1、多例类
class Restaurant:'''餐馆类'''def __init__(self,restaurant_name,cuisine_type):#类的属性self.restaurant_name = restaurant_nameself.cuisine_type = cuisine_type# self.stregth_level = 0def describe_restaurant(self):'''描述餐厅'''print(f'餐厅名字是{self.restaurant_name};菜品是{self.cuisine_type}')def open_reataurant(self):'''开餐厅'''print(f'{self.restaurant_name}餐厅正在营业')'''静态方法'''@staticmethoddef restaurant(a,b):print(a+b)'''类方法'''@classmethoddef myrestaurant(cls):Restaurant.restaurant(20,40) #类对象调用静态方法def mynerestaurant(self):self.restaurant(50,60) #类实例对象调用静态方法class Car:'''用户类'''def __init__(self,make,model,year):#类的属性self.make= makeself.model = modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):print(f'{self.year} {self.make} {self.model}')def read_odometer(self):print(f'This car has{self.odometer_reading} miles on it')def update_odometer(self,mileage):if mileage>=self.odometer_reading:self.odometer_reading=mileageelse:print(f'你不能退后')def increment_odometer(self,miles):self.odometer_reading+=milesdef fillgasoil(self):print('{self.make}加20L油')
2、单类
class User:'''用户类'''def __init__(self,first_name,last_name):#类的属性self.first_name = first_nameself.last_name = last_nameself.login_attemps=0# self.stregth_level = 0def printuserinfo(self):print(f'顾客全名{self.first_name}+{self.last_name}')def greetuserhello(self):print(f'顾客{self.first_name}+{self.last_name}您好')def increment_login_attemps(self):self.login_attemps += 1def reset_login_attemps(self):self.login_attemps=0'''静态方法'''@staticmethoddef descricbe_uesr(a,b):print(a+b)'''类方法'''@classmethoddef print_uesr(cls):User.printuserinfo()
3、类的调用干事情
from ClassUser import User
'''导入单个类'''myUser=User('王',"好汉")myUser.printuserinfo()
from 创建和使用类.ClassOne import Car
'''从同一级导入类'''mycar=Car('changan','cs45',15)
mycar.update_odometer(300)
from 创建和使用类.ClassOne import Restaurant,Car
'''从一个模块导入多个类'''myprivate=Restaurant('Chinesefood','france')
myprivate.open_reataurant()mypcar=Car('audi','r8',2)
mypcar.read_odometer()
from 创建和使用类.ClassOne import*
'''导入所有类'''
myprivate1=Restaurant('Chinesefood','france')
myprivate1.open_reataurant()mypcar1=Car('audi','r8',2)
mypcar1.read_odometer()
from 创建和使用类.ClassOne import Restaurant as CR
from 创建和使用类.ClassOne import Car as CC
'''使用别名'''myprivate=CR('Chinesefood','france')
myprivate.mynerestaurant()mycarx=CC('audi','r8',2)
mycarx.read_odometer()