basic programming python: Python objects, methods, classes, instances, function usage analysis

Analysis of the examples herein Python objects, methods, classes, instances, function usage. Share to you for your reference. Specific analysis is as follows:

Python is a fully object-oriented language. Examples are not only the objects, classes, functions, methods are also objects.

class Foo(object):
    static_attr = True
    def method(self):
        pass
foo = Foo()

This code is actually created two objects, Foo and foo. While at the same time is a class Foo, foo is an instance of this class.
Type definition is done in C ++ at compile time, is stored in static memory, it can not be easily modified. In Python types themselves are subject, and the instance objects as stored in the stack, the interpreter is for instance of the object class object and not fundamentally different.
In Python, every object has its own namespace. Variable in space are stored in the object's __dict__. Thus, Foo class has a __dict__, foo instance also has a __dict__, but are two different namespaces.
The so-called "definition of a class" was actually Mr. into a class object, and then execute a piece of code, but the local namespace when the class is set to execute the code of __dict__ so you can write code like this:

>>> class Foo(object):
...     bar = 1 + 1
...     qux = bar + 1
...     print "bar: ", bar
...     print "qux: ", qux
...     print locals()
...
bar:  2
qux:  3
{'qux': 3, '__module__': '__main__', 'bar': 2}
>>> print Foo.bar, Foo.__dict__['bar']
2 2
>>> print Foo.qux, Foo.__dict__['qux']
3 3

The so-called "definition of a function", in fact, is to generate a function object. The "define a method" that produces a
function of an object, and this object in a class __dict__. Form the following two definitions are equivalent methods:

>>> class Foo(object):
...     def bar(self):
...         return 2
...
>>> def qux(self):
...     return 3
...
>>> Foo.qux = qux
>>> print Foo.bar, Foo.__dict__['bar']
>>> print Foo.qux, Foo.__dict__['qux']

>>> foo = Foo()
>>> foo.bar()
2
>>> foo.qux()
3

The class inheritance is simply to define two class objects, each of which has different __dict__:

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...
>>> print Cheese.smell
good
>>> print Cheese.taste
good
>>> print Stilton.smell
bad
>>> print Stilton.taste
good
>>> print 'taste' in Cheese.__dict__
True
>>> print 'taste' in Stilton.__dict__
False

Complex in place .on the operator. For the class is, Stilton.taste means "in Stilton. Looking dict__ the 'taste'. If not found, the parent __dict__ Cheese's go, then the parent of the parent class, and so on. If you have been to object still is not found, then throw a AttributeError ".
examples also have their own __dict
:

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...     def __init__(self, weight):
...         self.weight = weight
...     def get_weight(self):
...         return self.weight
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...
>>> stilton = Stilton('100g')
>>> print 'weight' in Cheese.__dict__
False
>>> print 'weight' in Stilton.__dict__
False
>>> print 'weight' in stilton.__dict__
True

Whether __init __ () is defined where the, stilton .__ dict__ have nothing to do with class __dict__.
Cheese.weight and Stilton.weight go wrong, because these two are not touch namespace instance. The
search order stilton.weight is Stilton. Dict => Stilton. Dict =>
Cheese. Dict => Object. Dict . This is very similar to look Stilton.taste order, just
in front of more than a step.

The method is slightly more complicated.

>>> print Cheese.__dict__['get_weight']
>>> print Cheese.get_weight

>>> print stilton.get_weight
<__main__.Stilton object at 0x7ff820669190>>

We can see the dot operator the function into a class named unbound method to directly call functions and point in space.
Unbound method of operation will be returned by different error:

>>> Cheese.__dict__['get_weight']()
Traceback (most recent call last):
  File "", line 1, in
TypeError: get_weight() takes exactly 1 argument (0 given)
>>> Cheese.get_weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: unbound method get_weight() must be called with Cheese instance as
first argument (got nothing instead)

But it is one thing to say two errors, instance method requires an instance. The so-called "binding method" is simply a method call to an instance of an object as the first parameter. These calls the following methods are equivalent

>>> Cheese.__dict__['get_weight'](stilton)
'100g'
>>> Cheese.get_weight(stilton)
'100g'
>>> Stilton.get_weight(stilton)
'100g'
>>> stilton.get_weight()
'100g'

The last is the usual way with the call, stilton.get_weight (), is another feature point operator, the stilton.get_weight () translated into stilton.get_weight (stilton).
In this way, the method call actually has two steps. First, find a property rules found get_weight, then this property as a function call, and the first instance of an object as a parameter. No link between these two steps. For example, you can try this:

>>> stilton.weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'str' object is not callabl

Find weight to this property, then the weight as a function call. But weight is a string, so wrong. Find properties should be noted here is an example from the beginning:

>>> stilton.get_weight = lambda : '200g'
>>> stilton.get_weight()
'200g'

but

>>> Stilton.get_weight(stilton)
'100g'

Stilton.get_weight lookup skip Stilton instance of an object, it is found not to be covered, the method defined in Cheese.
getattr (stilton, 'weight') and stilton.weight are equivalent. Class object instance of the object and there is no essential difference, getattr (Cheese, 'smell' ) and Cheese.smell likewise equivalent. getattr () compared with the dot operator benefit is the attribute name specified string, it can be changed at run time.

getAttribute () is the underlying code. If you do not redefine this method, Object. GetAttribute () and type. GetAttribute () is getattr () is embodied, for example of the former, for the latter class. In other words, stilton.weight is Object. GetAttribute (Stilton, 'weight'). This cover is error prone. For example, the dot operator can lead to infinite recursion:

def __getattribute__(self, name):
        return self.__dict__[name]

getAttribute () There are other details, such as to achieve descriptor protocol, if it is easy to rewrite mistake.
getattr () method is called in to find __dict__ case not found. Generally dynamically generated attributes use this, because __getattr __ () does not interfere to put __dict__ defined elsewhere in the property.

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...     def __getattr__(self, name):
...         return 'Dynamically created attribute "%s"' % name
...
>>> stilton = Stilton()
>>> print stilton.taste
good
>>> print stilton.weight
Dynamically created attribute "weight"
>>> print 'weight' in stilton.__dict__
False

Since the method is only possible as a property function call, getattr () method can also be used to dynamically generate, but also have to pay attention to infinite recursion:

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...     def __init__(self, weight):
...         self.weight = weight
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...     def __getattr__(self, name):
...         if name.startswith('get_'):
...             def func():
...                 return getattr(self, name[4:])
...             return func
...         else:
...             if hasattr(self, name):
...                 return getattr(self, name)
...             else:
...                 raise AttributeError(name)
...
>>> stilton = Stilton('100g')
>>> print stilton.weight
100g
>>> print stilton.get_weight
>>> print stilton.get_weight()
100g
>>> print stilton.age
Traceback (most recent call last):
  File "", line 1, in
  File "", line 12, in __getattr__
AttributeError: age

Content on more than how many, and finally to recommend a good reputation in the number of public institutions [programmers], there are a lot of old-timers learning skills, learning experience, interview skills, workplace experience and other share, the more we carefully prepared the zero-based introductory information on actual project data every day to explain the timing of Python programmers technology, and share some learning methods need to pay attention to small detailsHere Insert Picture Description

Published 20 original articles · won praise 0 · Views 3616

Guess you like

Origin blog.csdn.net/chengxun02/article/details/104996434