python编程 您所在的位置:网站首页 导致用英文表示相近的词语 python编程

python编程

#python编程| 来源: 网络整理| 查看: 265

简单介绍python中的函数和类 导入函数模块先来一个简单的demo编写一个函数Dog.py继承导入类

导入函数模块

import ModuleName import ModuleName as m from module_name import function_0, function_1, function_2

先来一个简单的demo def greeting(name, msg='hello~'): print(name,msg) return 'greeting done' greeting('qingjia','nice to meet you~') qingjia nice to meet you~ greeting(msg='hi~',name='qingjia') qingjia hi~ greeting('qingjia') qingjia hello~ #得到返回值 print(greeting('qingjia')) greeting done

不定参数

def show(*language): print(language) show('Python') ('Python',) show('Python','JavaScript') ('Python', 'JavaScript') 编写一个函数Dog.py class Dog(): #__init__()是一个特殊的方法,每当你根据dog类创建新实例时,Python都会自动运行它 def __init__(self, name, age): self.name = name self.age = age def sit(self): print(self.name.title() + " is now sitting.")

在test.py中调用函数

import Dog a = Dog.Dog('wawa', 2) a.sit()

或者

from Dog import Dog a = Dog('wawa', 2) a.sit()

from Dog import * import语句中的星号让Python将模块pizza中的每个函数都复制到这个程序文件中。由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。但最好不要采用:如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果。

不清楚用了那些类名字的重复带来的问题

改变函数属性

#Method1: class Car(): def __init__(self, make, model, year): #initialize make, model, year self.odometer_reading = 0 my_new_car = Car('audi', 'a4', 2016) my_new_car.odometer_reading = 23 #Method2: def update_odometer(self, mileage): self.odometer_reading = mileage 继承

创建子类时,父类必须包含在当前文件中,且位于子类前面

class Car: def __init__(self, model): self.model = model class ElectricCar(Car): def __init__(self, model): super().__init__(model) self.electricity = 30 mycar = ElectricCar('tesla') print(mycar.electricity) class Car(): def __init__(self, model): self.model = model class Battery(): def __init__(self, batterysize=70): self.electricity = batterysize class ElectricCar(Car): def __init__(self, model): super().__init__(model) self.bat = Battery() mycar = ElectricCar('tesla') print(mycar.bat.electricity) # 创建一辆电动汽车,并将其存储在变量mycar中。要描述电瓶时,需要使用电动汽车的属性battery

在python 2.7中:

class Car(object): def __init__(self, make, model, year): #initialization class ElectricCar(Car): def __init__(self, make, model, year): super(ElectricCar, self).__init__(make, model, year)

重写方法 对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。为此,可在子类中定义一个这样的方法,即它与要重写的父类方法同名 在这里插入图片描述

导入类

from car import Car, ElectricCar car: car.py Car & ElectricCar: class

导入整个模块 import car car.py my_tesla = car.ElectricCar(‘tesla’, ‘roadster’, 2016)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有