面向对象作业

  • 编写程序, 编写一个学生类, 要求有一个计数器的属性, 统计总共实例化了多少个学生

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())
View Code
  • 编写程序, A 继承了 B, 俩个类都实现了 handle 方法, 在 A 中的 handle 方法中调用 B 的 handle 方法

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()
View Code
  • 编写程序, 在元类中控制自定义的类无需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)   #<__main__.Chinese object at 0x000001C63BC2CB70> china
print(p1.__dict__)      #{'name': 'alex', 'age': 18}
View Code
  • 编写程序, 在元类中控制把自定义类的数据属性都变成大写

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__)
View Code
  • 实现单例模式

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)
利用classmethod实现
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 )
自定义元类
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)
姿势3
原文地址:https://www.cnblogs.com/wenyule/p/9118794.html