悉野小楼

导航

python练习4 类相关操作

class MyClass:
    myNum = 0 #相当于类的变量
    def __init__(self, name):
        self.name = name
        self.data = 0
        MyClass.myNum += 1
        #print("self:", self)
        #print("__class__:", __class__)
    def getNum(self):
        return self.data
    def setNum(self, newNum):
        self.data = newNum
    

obj1 = MyClass("obj1")
obj1.setNum(2)
print(obj1.name, obj1.myNum)

obj2 = MyClass("obj2")
#可以用类名, 或变量名访问myNum
print(obj2.name, obj2.myNum, obj2.myNum, MyClass.myNum)

obj2.setNum(66)
print("getNum或直接访问", obj2.getNum(), obj2.data)

class BasedClass:
    def __new__(cls, *args, **kwargs):
        print("父类构造方法")
        return super(BasedClass,cls).__new__(cls)
        
    def __init__(self):
        print("父类init:", __class__)
        
    def parentMethod(self):
        print("调用父类方法parentMethod")
        
class DerivedClass(BasedClass):
    '''
    def __new__(cls, *args, **kwargs):
        print("子类构造方法")
        return super(DerivedClass,cls).__new__(cls)
    '''    
    def __init__(self):
        print("子类init:", __class__)
    
    def childMethod(self):
        print("调用子类ChildMethod")
        
        objDerived = DerivedClass() #会调用父类的__new__, 但不会调用父类的__init__
objDerived.childMethod()
objDerived.parentMethod()

# 实例化一个单例
class Singleton(object):
    __instance = None
    __first_init = False
    #cls表示当前类
    def __new__(cls, age, name):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __init__(self,age,name):
        if not self.__first_init:
            self.age = age
            self.name = name
            Singleton.__first_init = True

a = Singleton(18, "wk")
b = Singleton(8, "mm")

print(id(a)==id(b))

 再一个单例1:

class Single(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if cls._instance is None:
            cls._instance = object.__new__(cls, *args, **kw)
        return cls._instance
    def __init__(self):
        pass

single1 = Single()
single2 = Single()
print(id(single1) == id(single2))

再一个单例2:

def singleton(cls):
    _instance = {}

    def inner():
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]
    return inner
    
@singleton
class Cls(object):
    def __init__(self):
        pass

cls1 = Cls()
cls2 = Cls()
print(id(cls1) == id(cls2))

 

posted on 2023-10-14 20:06  悉野  阅读(3)  评论(0编辑  收藏  举报