How to display the "Python" Instance properties-dir, __dict__

Source: Internet
Author: User

There has been a misunderstanding when testing the properties of an instance.

class Test():    name = ‘python‘    def printest():        print ‘Test‘a = Test()print dir(a)print a.__dict__

where Dir (a) prints the content: ['doc', 'module', ' name ', ' Printest ']
Where A. dict print out: {}

Previously mistaken for Dir (a) as an existing attribute of instance a, the actual dir means: it returns a list that contains all the names of the properties that can be found, that is, the properties of the returned class and its subclasses, and a list of methods. For example, the Class A is Test,name is actually a class attribute.

The implication of Dict is that this property is to display the properties and values in the object in a dictionary. Note that this is the object, where the object is a, and instance a itself does not have any properties, so it is called {}. (Can use A.name access is due to the reason for looking up)

For example, to set a property for a, then see the printing of two functions.

class Test():    name = ‘python‘    def __init__(self):        self.lastname = ‘tttt‘    def printest():        print ‘Test‘a = Test()a.firstname = ‘hhh‘print dir(a)print a.__dict__

The printout is this:
['doc', 'init', 'module', ' FirstName ', ' LastName ', ' name ', ' Printest ']
{' LastName ': ' Tttt ', ' FirstName ': ' HHH '}
You can see that you have an instance property at this point.

How to display the "Python" Instance properties-dir, __dict__

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.