python学习第九天

Classes

#Classes
class Point:  #变量通常是小写,类第一个字母通常大写
    def move(self):
        print("move")
    def draw(self):
        print("draw")

point1=Point()
point1.x=10
point1.y=20
print(point1.x)
point1.draw()
point2=Point()
print(point2.x)#会报错,因为类里面没有定义x属性

Constructors

#Constructors
class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def move(self):
        print("move")
    def draw(self):
        print("draw")
point1=Point(10,20)
point1.x=11
print(point1.x)

exercise

class Person:
    def __init__(self,name):
        self.name=name
    def talk(self):
        print(f"{self.name} is talking!")
person1=Person("Wym")  
person1.talk()   #Wym is talking!
bob=Person("Bob")
bob.talk()   #Bob is talking!

Inheritance

#inheritance
class Mammal:
    def walk(self):
        print("walk")
class Dog(Mammal):  #不可以是空的
    #pass
    def bake(self):
        print("bake")
class Cat(Mammal):
    def be_annoying(self):
        print("annoying")
    pass
dog1=Dog()
dog1.walk()
dog1.bake()

Modules

在app.py文件中调用同级文件converters.py中的函数

import converters  #每一个文件是一个module
from converters import kg_to_lbs
print(kg_to_lbs(70))
print(converters.kg_to_lbs(70))

在这里插入图片描述
exercise

from utils import find_max
datas=[1,3,4,2,9,8,7]
maximum=find_max(datas)
print(maximum)

在这里插入图片描述

Packages

#packages
import ecommerce.shippinh
from ecommerce.shippinh import calc_shipping
from ecommerce import shippinh
ecommerce.shippinh.calc_shipping()
calc_shipping()
shippinh.calc_shipping()

在这里插入图片描述

Random

import random
names=["wym","jsy","tyw","lmy"]
leader=random.choice(names)
print(leader)
print(random.random())
print(random.randint(10,20))

产生随机元组

import random


class Dice:
    def roll(self):
        #random_tuple=(random.randint(0,10),random.randint(0,10))
        #return random_tuple
        first = random.randint(0, 10)
        second = random.randint(0, 10)
        return first, second


tu = Dice()
print(tu.roll())

注意,pycharm会提示code是否规范,一般import部分与定义class部分中间隔两行,class与实现调用中间隔两行,等号左右都空格,逗号后面跟一个空格

Files and Directories

#Files and Directories
from pathlib import Path


path = Path("ecommerce")
print(path.exists())
for file in path.glob("*.py"):
    print(file)

搜索模块pypi.org

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值