The Python Oracle

Python IsInstance() for classes and subclasses

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Python Isinstance() For Classes And Subclasses
02:04 Accepted Answer Score 2
03:28 Thank you

--

Full question
https://stackoverflow.com/questions/5038...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #class #multipleinheritance #pythondecorators

#avk47



ACCEPTED ANSWER

Score 2


  1. If SizedString is an instance of Descriptor ( based on Inheritance hierarchy- String , Typed , MaxSized, Descriptor ), then String and Integer also should satisfy the If condition right ? because at the end it is also the subclass of ( typed , Descriptor ) ?

    We have to look carefully at what is being passed into the check_attributes function. Look closer at what the value of the name and share keyword arguments are:

    @check_attributes(name=String,shares=Integer,place=SizedString('tester',size=8))
    

    Notice the lack of parenthesis after the String and Integer class names? This means the String and Integer class object themselves are being passed into check_attributes, not an instance of either class. And since the String class object and the Integer class object are not sub-classes of Descriptor, isinstance(value, Descriptor) fails.

  2. What is value(key) in setattr(cls, key, value(key)) means , cant understand what is value(key ) means ?

    Think about it. Since value has the value of whatever keyword argument was passed into check_attributes, and the value is not an instance of the Descriptor class, then value must be referring to a class object. (If you don't understand why this is, refer back to my answer to your first question). So calling value(key) is creating an instance of some class, and passing in the key value as a constructor argument.