• 面向对象进阶


    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>
    
    
    # 单例模式,但是地址不一样,不知道是哪里的问题
    

      

  • 相关阅读:
    H5页面获取屏幕宽高
    装修注意事项
    两列等高布局
    html/css
    css的几种垂直水平居中方法
    3分钟看懂flex布局
    Android手机里H5页面滚动图片时出现白屏
    JavaScript正则表达式——函数
    javascript正则表达式——语法
    【react】子组件向父组件传值
  • 原文地址:https://www.cnblogs.com/chenadong/p/9595565.html
Copyright © 2020-2023  润新知