-
编写程序, 编写一个学生类, 要求有一个计数器的属性, 统计总共实例化了多少个学生
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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())
-
编写程序, A 继承了 B, 俩个类都实现了 handle 方法, 在 A 中的 handle 方法中调用 B 的 handle 方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class B: def handle(self): print("B handle") class A(B): def handle(self): super().handle() # B.handle(self) print("a handle") a = A() a.handle()
-
编写程序, 在元类中控制自定义的类无需init方法.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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) #<__main__.Chinese object at 0x000001C63BC2CB70> china print(p1.__dict__) #{'name': 'alex', 'age': 18}
-
编写程序, 在元类中控制把自定义类的数据属性都变成大写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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__)
-
实现单例模式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 )
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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)