程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 tutorial: by__ dict__ And dir()

編輯:Python

Tell me about the problem I had :

class Demo:
def __init__(self, name, age):
self.name = name
self.age = age
def func(self):
print('Hello {0}'.format(self.name))
>>> d1 = Demo('Pythoner', 24)
>>> hasattr(d1, 'func')
True
>>> d1.__dict__
{
'age': 24, 'name': 'Pythoner'}
>>dir(d1)
[ 'age', 'func', 'name','__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

First , We know that instance methods can also be counted as attributes , adopt hasattr() Function can verify . and __dict__ Is a dictionary used to store object properties , But its return value does not contain ’func’!

Look again dir() function , It will automatically find all the attributes of an object ( Include properties inherited from the parent class ), Its return value contains ’func’.
So I guess ," Example method " Not belonging to an instance " private " attribute , It is a property shared by all instances of the class !
The instance needs a to get the private attribute " Privatization " The process of , It's like __init__ Initialization function !

verification :

''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
class Demo2:
def __init__(self, name):
self.name = name
def func(self):
print('----get arg country----')
self.country = 'China'
>>> d2 = Demo2('Pythoner')
>>> d2.__dict__
{
'name': 'Pythoner'}
>>> d2.func()
----get arg country----
>>> d2.__dict__
{
'country': 'China', 'name': 'Pythoner'}

" Example method " It is called an instance method , In other words, the execution of instance methods for each instance will produce different results due to different private properties , It is because of the self Parameters .

When an instance executes an instance method, it will look for the method in the class it belongs to , And then through self Parameters pass in the instance itself , The private attributes of the instance are passed together . adopt self Parameter implements the binding of instance and method .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved