search
HomeBackend DevelopmentPython TutorialPython中的对象,方法,类,实例,函数用法分析

本文实例分析了Python中的对象,方法,类,实例,函数用法。分享给大家供大家参考。具体分析如下:

Python是一个完全面向对象的语言。不仅实例是对象,类,函数,方法也都是对象。

复制代码 代码如下:
class Foo(object):
    static_attr = True
    def method(self):
        pass
foo = Foo()
这段代码实际上创造了两个对象,Foo和foo。而Foo同时又是一个类,foo是这个类的实例。
在C++里类型定义是在编译时完成的,被储存在静态内存里,不能轻易修改。在Python里类型本身是对象,和实例对象一样储存在堆中,对于解释器来说类对象和实例对象没有根本上的区别。
在Python中每一个对象都有自己的命名空间。空间内的变量被存储在对象的__dict__里。这样,Foo类有一个__dict__, foo实例也有一个__dict__,但这是两个不同的命名空间。
所谓“定义一个类”,实际上就是先生成一个类对象,然后执行一段代码,但把执行这段代码时的本地命名空间设置成类的__dict__. 所以你可以写这样的代码:
复制代码 代码如下:
>>> 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

所谓“定义一个函数”,实际上也就是生成一个函数对象。而“定义一个方法”就是生成一
个函数对象,并把这个对象放在一个类的__dict__中。下面两种定义方法的形式是等价的:

复制代码 代码如下:
>>> 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

而类继承就是简单地定义两个类对象,各自有不同的__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

复杂的地方在`.`这个运算符上。对于类来说,Stilton.taste的意思是“在Stilton.__dict__中找'taste'. 如果没找到,到父类Cheese的__dict__里去找,然后到父类的父类,等等。如果一直到object仍没找到,那么扔一个AttributeError.”
实例同样有自己的__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

不管__init__()是在哪儿定义的, stilton.__dict__与类的__dict__都无关。
Cheese.weight和Stilton.weight都会出错,因为这两个都碰不到实例的命名空间。而
stilton.weight的查找顺序是stilton.__dict__ => Stilton.__dict__ =>
Cheese.__dict__ => object.__dict__. 这与Stilton.taste的查找顺序非常相似,仅仅是
在最前面多出了一步。

方法稍微复杂些。

复制代码 代码如下:
>>> print Cheese.__dict__['get_weight']

>>> print Cheese.get_weight

>>> print stilton.get_weight
<__main__.stilton object at>>


我们可以看到点运算符把function变成了unbound method. 直接调用类命名空间的函数和点
运算返回的未绑定方法会得到不同的错误:
复制代码 代码如下:
>>> 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)
但这两个错误说的是一回事,实例方法需要一个实例。所谓“绑定方法”就是简单地在调用方法时把一个实例对象作为第一个参数。下面这些调用方法是等价的:
复制代码 代码如下:
>>> Cheese.__dict__['get_weight'](stilton)
'100g'
>>> Cheese.get_weight(stilton)
'100g'
>>> Stilton.get_weight(stilton)
'100g'
>>> stilton.get_weight()
'100g'
最后一种也就是平常用的调用方式,stilton.get_weight(),是点运算符的另一种功能,将stilton.get_weight()翻译成stilton.get_weight(stilton).
这样,方法调用实际上有两个步骤。首先用属性查找的规则找到get_weight, 然后将这个属性作为函数调用,并把实例对象作为第一参数。这两个步骤间没有联系。比如说你可以这样试:
复制代码 代码如下:
>>> stilton.weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'str' object is not callable
先查找weight这个属性,然后将weight做为函数调用。但weight是字符串,所以出错。要注意在这里属性查找是从实例开始的:
复制代码 代码如下:
>>> stilton.get_weight = lambda : '200g'
>>> stilton.get_weight()
'200g'
但是
复制代码 代码如下:
>>> Stilton.get_weight(stilton)
'100g'
Stilton.get_weight的查找跳过了实例对象stilton,所以查找到的是没有被覆盖的,在Cheese中定义的方法。

getattr(stilton, 'weight')和stilton.weight是等价的。类对象和实例对象没有本质区别,getattr(Cheese, 'smell')和Cheese.smell同样是等价的。getattr()与点运算符相比,好处是属性名用字符串指定,可以在运行时改变。

__getattribute__()是最底层的代码。如果你不重新定义这个方法,object.__getattribute__()和type.__getattribute__()就是getattr()的具体实现,前者用于实例,后者用以类。换句话说,stilton.weight就是object.__getattribute__(stilton, 'weight'). 覆盖这个方法是很容易出错的。比如说点运算符会导致无限递归:

复制代码 代码如下:
def __getattribute__(self, name):
        return self.__dict__[name]
__getattribute__()中还有其它的细节,比如说descriptor protocol的实现,如果重写很容易搞错。

__getattr__()是在__dict__查找没找到的情况下调用的方法。一般来说动态生成属性要用这个,因为__getattr__()不会干涉到其它地方定义的放到__dict__里的属性。

复制代码 代码如下:
>>> 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
由于方法只不过是可以作为函数调用的属性,__getattr__()也可以用来动态生成方法,但同样要注意无限递归:
复制代码 代码如下:
>>> 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

希望本文所述对大家的Python程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor