面向对象练习题
1、实现单例模式
姿势1,利用classmethod实现
class Mysql:
__instance = None
def __init__(self, host="127.0.0.1", post=9999):
self.host = host
self.post = post
@classmethod
def single(cls,):
if not cls.__instance:
cls.__instance = cls()
return cls.__instance
sql1 = Mysql()
sql2 = Mysql()
print(sql1 is sql2)
sql3 = Mysql.single()
sql4 = Mysql.single()
print(sql3 is sql4)
姿势2,自定义元类
class Mymeta(type):
__instance = None
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if not self.__instance:
super().__call__(*args, **kwargs)
# print('__instance',self.__instance)
return self.__instance
class Mysql(metaclass=Mymeta):
def __init__(self, host='127.0.0.1', post=9999):
self.host = host
self.post = post
a = Mysql()
b = Mysql()
print(a is b )
姿势3
class Singleton:
__instance = None
def __new__(self, *args, **kwargs):
if not self.__instance:
super().__new__(self, *args, **kwargs)
p1 = Singleton()
p2 = Singleton()
print(p1 is p2)
2、编写程序, 在元类中控制把自定义类的数据属性都变成大写
class Mymeta(type):
def __new__(cls,name, bases, dics):
update_dic = {}
for k,v in dics.items():
if not callable(v) and not k.startswith("__"):
update_dic[k.upper()] = v
else:
update_dic[k] = v
return type.__new__(cls,name, bases, update_dic)
class Chinese(metaclass=Mymeta):
country = "china"
sex = 'male'
print(Chinese.__dict__)
3、编写程序, 在元类中控制自定义的类无需init方法.
class MyMeta(type):
def __call__(self, *args, **kwargs):
if args:
raise typeError("must be keyword argument")
obj = object.__new__(self)
for k, v in kwargs.items():
obj.__dict__[k]=v
return obj
class Chinese(metaclass=MyMeta):
country = 'china'
p1 = Chinese(name='alex', age=18)
print(p1, p1.country)
print(p1.__dict__)
4、编写程序, 编写一个学生类, 要求有一个计数器的属性, 统计总共实例化了多少个学生.
class Student:
i = 0
def __init__(self, name):
self.name = name
Student.i += 1
@classmethod
def count(cls):
return cls.i
a = Student("a")
b = Student("b")
print(Student.count())
5、编写程序, A 继承了 B, 俩个类都实现了 handle 方法, 在 A 中的 handle 方法中调用 B 的 handle 方法
class B:
def handle(self):
print("B handle")
class A(B):
def handle(self):
super(A, self).handle()
print("a handle")
a = A()
a.handle()