zoukankan      html  css  js  c++  java
  • 面向对象进阶

    class Foo(object):
    	def __init__(self, name, age):
    		self.name = name
    		self.age = age
    
    	def __getitem__(self, item):
    		if hasattr(self, item):
    			return self.__dict__[item]
    
    	def __setitem__(self, key, value):
    		self.__dict__[key] = value
    
    	def __delitem__(self, key):
    		del self.__dict__[key]
    
    
    foo = Foo("adong", "28")
    print foo["name"], foo["age"]
    
    foo["height"] = "175"
    print foo["height"]
    
    del foo["height"]
    print foo["height"]
    
    >>>
    adong 28
    175
    None
    

      

    class F:
    	def __init__(self, name):
    		self.name = name
    
    	def __new__(cls, *args, **kwargs):
    		return object.__new__(cls)
    
    
    f1 = F("adong")
    f2 = F("aqiang")
    
    print f1
    print f2
    >>>
    <__main__.F instance at 0x0000000003A70E88>
    <__main__.F instance at 0x0000000003A70E48>
    
    # 实例化的结果是两个对象
    

      

    class F:
    	__instance = False
    
    	def __init__(self, name):
    		self.name = name
    
    	def __new__(cls, *args, **kwargs):
    		if cls.__instance:
    			return cls.__instance
    		else:
    			cls.__instance = object.__new__(cls)
    			return cls.__instance
    
    
    f1 = F("adong")
    f2 = F("aqiang")
    
    print f1
    print f2
    >>>
    <__main__.F instance at 0x0000000003A90E88>
    <__main__.F instance at 0x0000000003A90EC8>
    
    
    # 单例模式,但是地址不一样,不知道是哪里的问题
    

      

  • 相关阅读:
    KVM快速构建虚拟机
    工程师测试
    配置SMB,NFS
    Shell脚本基础应用
    Web网页部署
    基础邮件,mariadb数据库
    SElinux,firewalld配置
    Linux管理员测试
    磁盘分区
    配置权限,LDAP
  • 原文地址:https://www.cnblogs.com/chenadong/p/9595565.html
Copyright © 2011-2022 走看看