用python3编写一箭穿心_Python3 面向对象小练习

定义MySQL类

对象有id、host、port三个属性

定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一

提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化

为对象定制方法,save和get_obj_by_id,save能自动将对象序列化到文件中,文件路径为配置文件中 DB_PATH,文件名为id号,保存之前验证对象是否已经存在,若存在则抛出异常,get_obj_by_id方法用来从文件中反序列化出对象

from conf import settings

import uuid

import pickle

import os

class MySQL:

def __init__(self, host, port):

self.id = self.create_id()

self.host = host

self.port = port

def save(self):

if self.is_exists:

raise PermissionError('对象已存在')

file_path = f'{settings.DB_PATH}{os.sep}{self.id}'

pickle.dump(self, open(file_path, 'wb'))

@property

def is_exists(self):

tag = False

files = os.listdir(settings.DB_PATH)

for file in files:

file_abspath = f'{settings.DB_PATH}{os.sep}{file}'

obj = pickle.load(open(file_abspath, 'rb'))

if self.host == obj.host and self.port == obj.port:

tag = True

break

return tag

@staticmethod

def get_obj_by_id(id):

file_path = f'{settings.DB_PATH}{os.sep}{id}'

return pickle.load(open(file_path, 'rb'))

@staticmethod

def create_id():

return str(uuid.uuid1())

@classmethod

def from_conf(cls):

print(cls)

return cls(settings.HOST, settings.PORT)

# conn = MySQL.from_conf()

# conn.save()

obj = MySQL.get_obj_by_id('504ab0f6-ec21-11e9-b9e2-d053497faa26')

print(obj.host)

定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放

from math import pi

class Round:

def __init__(self, radius):

self.__radius = radius

def perimeter(self):

return round(2 * pi * self.__radius, 2)

def area(self):

return round(pi * (self.__radius ** 2), 2)

r = Round(1)

print(r.area())

print(r.perimeter())

print(r._Round__radius)

使用abc模块定义一个phone抽象类 并编写一个具体的实现类

import abc

# 抽象类/父类

class CellPhone(metaclass=abc.ABCMeta):

@abc.abstractmethod

def calling(self):

pass

@abc.abstractmethod

def send_msg(self):

pass

# 现实类/子类

class SmartPhone(CellPhone):

def calling(self):

print('calling...')

def send_msg(self):

print('sending msg...')

def app_download(self):

print('downloading app...')

iphone = SmartPhone()

iphone.calling()

iphone.send_msg()

iphone.app_download()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值