def fun_car(name,number,**anything): anything['name']=name anything['number']=number return anything car=fun_car('sinaru','outback',color='blue',tow_package=True) for key,value in car.items(): print(f"there is {key.title()} of {value}") #将函数储存在模块中 #和C++头文件是一回事 import pizza pizza=pizza.make_pizza('a','b',c='c',d='d',e='e') for key,value in pizza.items(): print(f"ok,what's the {key} in your {value}.".title()) #or pythpn还支持仅仅导入某一个函数 from pizza import make_pizza pizza=make_pizza('a','b',c='c',d='d',e='e')#不用再调用句点运算符了 print(pizza) #使用as起别名的功能 from pizza import make_pizza as mp pizza=mp('a','b',c='c',d='d',e='e') #成功输出 print(pizza) #标准 #from module_name import function_name as fn #as也可用来为库定义别名 #for example import pizza as p print(p.make_pizza('a','b',c='c',d='d',e='e')) #使用星号导入库中的所有函数 from pizza import * p=make_pizza('a','b',c='c',d='d',e='e') print(p) #这样也可以省一个句点运算符 #但是尽量避免函数名重复 #python在这种情况会覆盖部分函数 #所有少用这种语法 #import最好放在文件开头 #为了代码可读性 #面向对象编程 import class_dog as cd dog=cd.Dog('Jack',11) dog.roll() dog.sit() print(f"my dog's name is {dog.name}.and it has been {dog.age} years old.") #python的类与C++中的类是不一样的 #所有,python没有访问控制运算符? import Restaurant as Rest r1=Rest.Restaurant('abab','teda') print(f"the name is {r1.restaurant_name} and the type is {r1.cuisine_type}.".title()) r1.describe_restaurant() r1.open_restaurant() #将import放在文件中是很不好的习惯,这里仅仅作为学习笔记 r2=Rest.Restaurant('az','okok') r3=Rest.Restaurant('nishuo','guqa') r2.describe_restaurant() r3.describe_restaurant() import user u1=user.User('Jack','Heiqiu','a','b','c') u1.describe_user() u2=user.User('Jack','ahh','a','d',1,True) u2.describe_user() #python虽然没有良好的封装性 #但是其用法更加灵活
# @File : class_dog.py # @Software: PyCharm class Dog:#类的定义没有圆括号(C++也没有)python中最好将类的首字母大写 ''' 一次模拟小狗的简单尝试 ''' def __init__(self,name,age):#self是一个指向实例本身的引用,和C++的this指针起着同样的作用 '''初始化(C++的构造函数)''' self.name=name self.age=age def sit(self): '''模拟小狗收到信号蹲下(与C++产生了逻辑上的不同)''' print(f"{self.name} is now sitting.") def roll(self): '''模拟打滚''' print(f"{self.name} is now rolling.")
# @File : pizza.py # @Software: PyCharm def make_pizza(name,number,**sth): sth['name']=name sth['number']=number return sth
# @File : Restaurant.py # @Software: PyCharm class Restaurant: def __init__(self,restaurant_name,cuisine_type): self.restaurant_name=restaurant_name self.cuisine_type=cuisine_type def describe_restaurant(self): print(f"here is a restaurant named {self.restaurant_name} and the cuisine is {self.cuisine_type}.".strip()) def open_restaurant(self): print("ok,the restaurant is now opening.".title())
# @File : user.py # @Software: PyCharm class User: def __init__(self,first,last,*otherThing): self.first_name=first self.last_name=last self.other_thing=otherThing def describe_user(self): print(f"there is a user named {self.first_name+' '+self.last_name}.") print('and there are other things about him:') for item in self.other_thing: print(item) def greet_user(self): print(f"hei,{self.first_name+' '+self.last_name}.")