"Back to the beauty of Python" "Class-built-in function" Issubclass,isinstance,hasattr,getattr,setattr,delattr,dir,super,vars

Source: Internet
Author: User
Tags vars


Class-Built-in functions



Services to classes and objects.






9 Built-in functions



Issubclass,isinstance,hasattr,getattr,setattr,delattr,dir,super,vars



Note: GetAttr () and delattr () may throw exceptions (such as Attributeerror) to handle exceptions in conjunction with Try......expect



Note: Use Hasattr to assist Getattr,setattr,delattr, first use hasattr to Judge attr existence and then operation Getattr,setattr,delattr, ensure the robustness of the program, etc.






How to use.



See Sample code for details






Sample code


#encoding: utf-8
# ex_class_builtin_method.py
self_file = __file__

#issubclass, isinstance
#hasattr, getattr, setattr, delattr
#dir, super, vars

#Note: getattr () and delattr () may throw exceptions (such as AttributeError). You must combine try ... expect to handle exceptions

print "=================================================== ============= "
class CA (object):
    pass

class CB (CA): #CB is a subclass of CA
    pass

class CC (CB): #CC is a subclass of CB and CC is a subclass of CA
    pass

class CD:
    pass

print "\ n ====== issubclass (subclass, classes) ======"
#issubclass (subclass, classes)
#Return value: bool
#classes can be: int, float, bool, complex, str, list, dict, set, tuple
#True if subclass is a subclass of classes
#If subclass is not a subclass of classes, return False

print issubclass (CB, CA) #True
print issubclass (CB, (CA, CD)) #True
print issubclass (CC, CA) #True
print issubclass (CC, CB) #True
print issubclass (CD, CA) #False

print "\ n ====== isinstance (instance, classinfo) ======"
print isinstance (CB (), CB) #True
print isinstance (CB (), CA) #True
print isinstance (CB (), (CB, CD)) #True
print isinstance (CB (), CD) #False

print "\ n ====== isinstance (instance, classinfo)"
print isinstance (1, int) #True
print isinstance (1.0, float) #True
print isinstance (True, bool) #True
print isinstance (False, bool) #True
print isinstance ("Hi", str) #True
print isinstance (1 + 2j, complex) #True
print isinstance ([1,2], list) #True
print isinstance ({1,2}, set) #True
print isinstance ((1,2), tuple) #True
print isinstance ({1: "1", 2: "2"}, dict) #True
print isinstance (1, float) #False
print isinstance (1, (int, float)) #True

print "=================================================== ============= "
print "\ n ====== hasattr (instance, attr) ====="
#Return value: bool
#True if instance has attr, otherwise false
# instance-object,
# attr-string, attribute name

class CStudent (object):
    _ver = "Ver.1.0"
    def __init __ (self, age):
        self.age = age
    def foo (self):
        pass
print hasattr (CStudent (16), "__dict__") #True
print hasattr (CStudent (16), "_ver") #True
print hasattr (CStudent (16), "age") #True
print hasattr (CStudent (16), "__init__") #True
print hasattr (CStudent (16), "foo") #True

class CTeacher (object):
    pass
print hasattr (CTeacher (), "__init__") #False

class CPerson (object):
    def run (self):
        pass
class CWorker (CPerson):
    pass
print hasattr (CWorker (), "run") #True

print "\ n ====== getattr (instance, attr [, default_ret]) ======"
#Return Value: attrValue, defaultValue, Error AttributeError
#If attr exists, return the value of attr
#If default_ret is provided, getattr returns default_ret when attr does not exist
#If default_ret is not provided, getattr will trigger an exception AttributeError when attr does not exist

print getattr (CStudent (16), "age") # 16
print getattr (CStudent (16), "age", False) # 16
print getattr (CStudent (16), "name", False) #False
#print getattr (CStudent (16), "name") #Trigger exception AttributeError: CStudent instance has no attribute 'name'

print "\ n ====== setattr (instance, attr, value) ======"
#Return value: None
#instance must have attr attribute
#Set the value of the attribute attr of instance to value
tom = CStudent (16)
print getattr (tom, "age")
setattr (tom, "age", 17)
print getattr (tom, "age")

setattr (tom, "_ver", "Ver.2.0")
print getattr (tom, "_ver") # Ver.2.0
print CStudent._ver # Ver.1.0

#Please do not use setattr for non-existing attr!
print setattr (tom, "non-existent", 1) #None
print getattr (tom, "non-existent") # 1

print "\ n ====== delattr (instance, attr) ======"
#Return Value: None, ExceptionError
#Delete the attr attribute of instance

tom = CStudent (16)
if hasattr (tom, "age"): #True
    delattr (tom, "age") #None
    print getattr (tom, "age", False) #False
    #print getattr (tom, "age") #AttributeError: CStudent instance has no attribute 'age'
    #delattr (tom, "name") #AttributeError: CStudent instance has no attribute 'name'
else:
    pass


print "=================================================== ============= "
class CMachine (object): # 新式 类
    def hello (self):
        print "invoke hello in CMachine"

class CThing (object): # 新式 类
    def hello (self):
        print "invoke hello in CThing"

class CCar (CMachine, CThing):
    "I am CCar class"
    _ver = "1.0"
    def __init __ (self, name, money):
        self.name = name
        self.money = money
    def hello (self):
        print "invoke hello in CCar"
    def TestSuper (self):
        super (CCar, self) .hello () # super first select the first parent class with hello method from the parent class collection of CCar .__ mro__, and then call the hello method of this parent class
print "\ n ====== __ mro __ ======"
print CCar .__ mro __ # (<class '__main __. CCar'>, <class '__main __. CMachine'>, <class '__main __. CThing'>, <type 'object'>)

print "\ n ====== dir () ======"
print dir (CCar)
print dir (CCar ("BYD", 16))

print "\ n ====== super ======"
car = CCar ("BYD", 16)
car.TestSuper ()

print "\ n ====== vars ======"
print vars (CCar)

print "\ n ====== __ dict __ ======"
print CCar .__ dict__

print "\ n ====== __ mro __ ======"
class CAnimal: #Classic Class
    def hello (self):
        print "invoke hello in CAnimal"
class CMagic: #Classic Class
    def hello (self):
        print "invoke hello in CThing"
class CMonkey (CAnimal, CMagic):
    def TestSuper (self):
        pass
        #super (CMonkey, self) .hello () #TypeError: super () argument 1 must be type, not classobj
        #Indicate that the classic class no longer supports super
function

print "\ nexit% s"% self_file


Compile execution


============== RESTART: C:\Python27\ex_class_builtin_method.py ==============
============================================================

======issubclass(subclass, classes)======
True
True
True
True
False

======isinstance(instance, classinfo)======
True
True
True
False

======isinstance(instance, classinfo)
True
True
True
True
True
True
True
True
True
True
False
True
============================================================

======hasattr(instance, attr)=====
True
True
True
True
True
True
True

======getattr(instance, attr[, default_ret])======
16
16
False

======setattr(instance, attr, value)======
16
17
Ver.2.0
Ver.1.0
None
1

======delattr(instance, attr)======
False
============================================================

======__mro__======
(<class '__main__.CCar'>, <class '__main__.CMachine'>, <class '__main__.CThing'>, <type 'object'>)

======dir()======
['TestSuper', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_ver', 'hello']
['TestSuper', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_ver', 'hello', 'money', 'name']

======super======
invoke hello in CMachine

======vars======
{'__module__': '__main__', 'TestSuper': <function TestSuper at 0x0000000002E0BC88>, '_ver': '1.0', 'hello': <function hello at 0x0000000002E0BC18>, '__init__': <function __init__ at 0x0000000002E0BBA8>, '__doc__': 'I am CCar class'}

======__dict__======
{'__module__': '__main__', 'TestSuper': <function TestSuper at 0x0000000002E0BC88>, '_ver': '1.0', 'hello': <function hello at 0x0000000002E0BC18>, '__init__': <function __init__ at 0x0000000002E0BBA8>, '__doc__': 'I am CCar class'}

======__mro__======

exit C:\Python27\ex_class_builtin_method.py
>>> 
(end)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.