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 .