悉野小楼

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   悉野  阅读(6)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示