Python 내장 함수 delattr 의 구체 적 인 용법

13540 단어 Pythondelattr
delattr 함 수 는 속성 을 삭제 하 는 데 사 용 됩 니 다.
delattr(x,foobar)는 del x.foobar 와 같다.
문법
setattr 문법:delattr(object,name)
매개 변수
  • object--대상.
  • name--대상 의 속성 이 어야 합 니 다.
  • 영문 문서:
    delattr(object, name) 
    이것 은 setattr()의 상대 값 입 니 다.인 수 는 객체 와 문자열 입 니 다.캐릭터 라인 은 객체 의 속성 중 하나 여야 합 니 다.객체 가 허용 하 는 경우,함수 가 지 정 된 속성 을 삭제 합 니 다.예 를 들 어 delattr(x,'foobar')는 del x.foobar 와 같 습 니 다.설명:
    정의 클래스
    
    #coding=utf-8
    # class_my.py     (   )
    
    #    
    class Person:
      #     (class) ( : /          ;          ,         )
      name = "name" #     
      __adress = "adress" #      (__       )
    
      #     (      ) (__init__     )
      def __init__(self, name, address = "  "):
        #     
        self.name = name # ( :                  ,             )
        self.__adress = address
        Person.setData(self)
    
      #     (      ) (__del__     )
      def __del__(self):
        print("     .")
    
      # toString()
      def __str__(self):
        return "Person.class"
    
      #      (this)
      def setName(self, name): # self        (this)
        self.name = name; #         (       )
    
      #     (static)
      @classmethod
      def setName_cls(cls, name):
        cls.name = name #       
    
      #      (tools)
      @staticmethod
      def setName_sta(name): # ( :    )
        return name
    
      def getName(self):
        return self.name
    
      def setData(self):
        #     
        self.__age = 21 #     
        self.sex = " " #     
    
      def show(self):
        print("Hello! %s"%self.name)
        print("Address:%s"%self.__adress) #         
        self.__eat() #         
    
      def __eat(self): #     
        print("eat")
    
    
    
    # =======      ======
    if __name__ == "__main__":
      # -      -
      ps = Person("LY")
    
      # ---      ---
      #       
      ps.setName("LY") #          
      ps.show()
    
      #      
      Person.setName_cls("Person") #        
      ps.setName_cls("Person") #         
    
      #        ()
      print(ps.setName_sta("Per")) #          
      print(Person.setName_sta("Per")) #         
    
      # ---      ---
      print(ps.getName())
      print(ps.name) #              
      print(ps.sex) #               
    
      # ---      ---
    
      #       
      ps.name = "123" #        ( :     ,               )
      del ps.name #         ( :    (    )      ,                ,       )
      del ps.sex #         ( :   ,       )
    
      #      
      Person.name = "Person" #      
      Person.setName_cls("Person") #                 ( :         )
      ps.setName_cls("Person") #                 
      del Person.name #      
    
      # -      -
      del ps
      # > Less is more! "    " "   /  "       "  ",          ,   /         ,      ,             . (--       )
    # =======      ======
    
    이어받다
    
    #coding=utf-8
    # class_extend.py   (   )
    
    # ---     ---
    #   
    class Animal(object):
    
      def __init__(self, name = "  "):
        self.name = name
    
      def run(self):
        print("%s  ."%self.name)
    
    #   
    class Cat(Animal): #    (   () )
    
      def __init__(self, name, ot = ""):
        super(Cat, self).__init__(name)
    
      def miao(self):
        print(" ")
    
    
    
    # ---     ---
    class Donkey: #  
      def walk(self):
        print("walk")
    
      def eat(self):
        print("Donkey.eat")
    
    class Horse: #  
      def run(self):
        print("run")
    
      def eat(self):
        print("Horse.eat")
    
    class Mule(Donkey, Horse): #  ( + )
      pass
    
    
    
    # ===    ====
    def animalRun(animal): #              
      animal.run()
    
    
    
    
    # =======      ======
    if __name__ == "__main__":
      # -       -
      ani = Animal()
      ani.run()
    
      cat = Cat(" ")
      cat.run()
      cat.miao()
    
    
      # -       -
      mule = Mule()
      mule.walk()
      mule.run()
      mule.eat() #             ,  ()       (Donkey)   
    
    
      # -      -
      ani = Animal()
      animalRun(ani)
    
      cat = Cat(" ")
      animalRun(cat)
    # =======      ======
    
    
    다시 쓴다
    
    #coding=utf-8
    # class_rewrite.py   (   )
    
    class Animal(object):
    
      def run(self):
        print("Animal.run")
    
      def eat(self, food = "  "):
        print("eat:%s"%food)
    
    
    class Cat(Animal):
    
      #           
      def run(self):
        print("Cat.run")
    
      def eat(self):
        #        
        super(Cat, self).eat("  ")
    
    
    
    # =======      ======
    if __name__ == "__main__":
      ani = Animal()
      ani.run()
      ani.eat()
      cat = Cat()
      cat.run()
      cat.eat()
    # =======      ======
    
    
    속성 방법
    
    #!/usr/bin/env python
    # coding=utf-8
    __author__ = 'Luzhuo'
    __date__ = '2017/5/13'
    # class_propertiemethod.py     
    #     :          
    
    
    #   1
    class PM_1(object):
      def __init__(self):
        self.__name_str = "PropertieMethod_1"
    
      #   
      @property
      def name(self): #   ,     
        return self.__name_str
    
      #   
      @name.setter
      def name(self, name):
        self.__name_str = name
    
      #   
      @name.deleter
      def name(self):
        del self.__name_str
    
    
    if __name__ == "__main__":
      pm = PM_1()
      print(pm.name)
      pm.name = "PM"
      print(pm.name)
      del pm.name
      # print(pm.name)
    
    # ==========================================================
    
    
    #   2
    class PM_2(object):
      def __init__(self):
        self.__name_str = "PropertieMethod_2"
    
      #   
      def getname(self):
        return self.__name_str
    
      #   
      def setname(self, name):
        self.__name_str = name
    
      #   
      def delname(self):
        del self.__name_str
    
      # property(fget=None, fset=None, fdel=None, doc=None) #     property   ,               property_my    (http://blog.csdn.net/rozol/article/details/70603230)
      name = property(getname, setname, delname)
    
    
    if __name__ == "__main__":
      p = PM_2()
      print(p.name)
      p.name = "PM2"
      print(p.name)
      del p.name
      # print(p.name)
    
    
    반사
    
    #!/usr/bin/env python
    # coding=utf-8
    __author__ = 'Luzhuo'
    __date__ = '2017/5/13'
    # class_reflection.py   
    #       ,             /  /  
    # Python         ?  Android Java          gc,    UI   ,     
    # Python     (1    ):        :        = 1:1.164 ;       :        = 1:1.754
    
    def setname(self, name):
      self.name = name
    
    class Clazz(object):
      def __init__(self):
        self.name = "Clazz"
    
      def getname(self):
        return self.name
    
    
    
    if __name__ == "__main__":
      c = Clazz()
    
      # ---    ---
      if hasattr(c, "getname"):
        #   
        method = getattr(c, "getname", None)
        if method:
          print("setname_ref: {}".format(method())) #          
    
      if not hasattr(c, "setname"):
        #   
        setattr(c, "setname", setname) #     
        method = getattr(c, "setname", None)
        if method:
          method(c, "Reflection")
        print("setname_raw: {}".format(c.getname()))
    
      if hasattr(c, "setname"):
        #   
        delattr(c, "setname")
        # c.setname(c, "Demo")
    
    
      # ---    ---
      if not hasattr(c, "age"):
        #   
        setattr(c, "age", 21) #     
        var = getattr(c, "age", None)
        print("age_ref: {}".format(var))
        print("age_raw: {}".format(c.age))
    
      if hasattr(c, "age"):
        #   
        var = getattr(c, "age", None)
        print("age_ref: {}".format(var))
    
      if hasattr(c, "age"):
        #   
        delattr(c, "age")
        # print("age_raw: {}".format(c.age))
    
    
    문서 설명
    
    #!/usr/bin/env python
    # coding=utf-8
    __author__ = 'Luzhuo'
    __date__ = '2017/5/13'
    # class_doc.py     
    #        
    
    class Foo(object):
      '''
           
      '''
    
      def method(self, data):
        '''
              
        :param data:      
        :return:      
        '''
        return "method"
    
    
    def func(data):
      '''
            
      :param data:      
      :return:      
      '''
      return "func"
    
    
    
    if __name__ == "__main__":
      #     
      print(Foo.__doc__)
      print(Foo().method.__doc__)
    
      print(func.__doc__)
    
    
    클래스 생 성 원리
    
    #!/usr/bin/env python
    # coding=utf-8
    __author__ = 'Luzhuo'
    __date__ = '2017/5/13'
    # class_origin.py     
    #   type      ,  type      
    
    age = 21
    
    def __init__(self):
      self.name = "origin"
    
    def getname(self):
      return self.name
    
    def setname(self, name):
      self.name = name
    
    def delname(self):
      del self.name
    
    
    if __name__ == "__main__":
      #  type   (  ,     ,      )
      Foo = type('Foo', (object,), {'__init__' : __init__, "getname" : getname, "setname" : setname,
                     "delname": delname, "age" : age})
      #     
      f = Foo()
      #   
      print(f.age)
      print(f.getname())
      f.setname("ClassOrigin")
      print(f.getname())
      f.delname()
      # print(f.getname())
    
    # ==================================================================================
    
    
    
    
    
    #    (type     )
    #             , Python  type  (  ,     ,        ,      ),      type    
    
    # __call__     (__new__ __init__    , __call__        )
    class Foobar(object):
      def __call__(self, *args, **kwargs):
        print("Foobar __call__")
    
    if __name__ == "__main__":
      fb = Foobar()
      fb() #            __call__  
    
      Foobar()() #       
    
    # ------
    
    
    # metaclass        
    # Python       __metaclass__  ,(    )           type
    class MyType(type):
      def __init__(self, *args, **kwargs):
        print("MyType __init__")
    
      def __call__(self, *args, **kwargs):
        print("MyType __call__")
        obj = self.__new__(self)
        self.__init__(obj, *args, **kwargs)
        return obj
    
      def __new__(cls, *args, **kwargs):
        print("MyType __new__")
        return type.__new__(cls, *args, **kwargs)
    
    
    class Foo(object, metaclass=MyType): # (Python3.x  ) metaclass      , Python       __metaclass__  ,(    )           type
    
      # __metaclass__ = MyType # Python2.x  
    
      def __init__(self):
        print("Foo __init__")
    
      def __new__(cls, *args, **kwargs): #        
        print("Foo __new__")
        return object.__new__(cls) #      
    
      def show(self):
        print("Foo show")
    
    
    if __name__ == "__main__":
      print("start")
      f = Foo()
      f.show()
      # MyType __new__ => MyType __init__ => 'start' => MyType __call__ => Foo __new__ => Foo __init__ => 'Foo show'
    
    
    기타
    
    #!/usr/bin/env python
    # coding=utf-8
    __author__ = 'Luzhuo'
    __date__ = '2017/5/13'
    # class_other.py         
    
    
    class Demo(object):
      def show(self):
        print("Demo show")
    
    if __name__ == "__main__":
      # __module__        
      # __class__        
      print(Demo.__module__) #         => __main__
      print(Demo.__class__) #         => <class 'type'>
    
      obj = Demo()
      print(obj.__module__) #         => __main__
      print(obj.__class__) #         => <class '__main__.Demo'>
      obj.__class__.show(obj) #        
    
      # ============================
    
      # __dict__           
      print(Demo.__dict__) #    
      print(obj.__dict__) #     
    
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기