The understanding of __dict__ in class, Python3__python

Source: Internet
Author: User

Class Friends (): #定义一个类

def __init__ (self):

Self.name = ' Wuq ' #两个实例变量

Self.gender = ' female '


Def say_to_friend (): #有一个方法

Print (' Hello%s '%self.name)


if __name__ = = ' __main__ ':

f = Friends () #创建实例

Print (f.__dict__) #输出为 {' name ': ' Wuq ', ' gender ': ' Female '}

Print (friends.__dict__)

'''

Output a heap,

{' __modul__ ': ' __main__ ', ' __init__ ': <function friends.__init__ at 0x000000000022fe730>,...

' __doc__ ': None} in the module ... Wait


In fact, the instance's __dict__ only has the instance properties associated with the instance.

The __dict__ property of an instance also makes instance properties of each instance not interact with each other, and an instance property of an instance is those associated with TA.


F.message = ' Hello my world ' #在外部添加一个实例属性 dynamically add a property

F.fun = lambda:x #实例属性为一个函数

Print (f.__dict__) #输出则为 {' name ': ' Wuq ', ' gender ': ' Female ', ' message ': ' Hello Me World ', ' fun ': <function <lambda > at 0x00000000001f8e7b8> final fun, function is the corresponding memory address


The __dict__ of an instance has instance variables and functions associated with the instance.


The __dict__ of a class is a variable that is shared with an instance, a function (method, class property). Note that the __dict__ of a class does not contain the properties of its parent class.

For example, direct print (object.__dict__)

The __dict__ of a subclass does not contain the __dict__ of the parent class.

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.