Home Backend Development Python Tutorial Python中的对象,方法,类,实例,函数用法分析

Python中的对象,方法,类,实例,函数用法分析

Jun 10, 2016 pm 03:18 PM
python function Example object method usage kind

本文实例分析了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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles