search
HomeBackend DevelopmentPython TutorialPython中Class类用法实例分析

本文实例讲述了Python中Class类用法。分享给大家供大家参考,具体如下:

尽管Python在Function Programming中有着其他语言难以企及的的优势,但是我们也不要忘了Python也是一门OO语言哦。因此我们关注Python在FP上的优势的同时,还得了解一下Python在OO方面的特性。

要讨论Python的OO特性,了解Python中的Class自然是首当其冲了。在Python中定义class和创建对象实例都很简单,具体代码如下:

class GrandPa:
  def __init__(self):
    print('I\'m GrandPa')
class Father(GrandPa):
  def __init__(self):
    print('I\'m Father!')
class Son(Father):
  """A simple example class"""
  i = 12345
  def __init__(self):
    print('这是构造函数,son')
  def sayHello(self):
    return 'hello world'
if __name__ == '__main__':
  son = Son()
  # 类型帮助信息 
  print('类型帮助信息: ',Son.__doc__)
  #类型名称
  print('类型名称:',Son.__name__)
  #类型所继承的基类
  print('类型所继承的基类:',Son.__bases__)
  #类型字典
  print('类型字典:',Son.__dict__)
  #类型所在模块
  print('类型所在模块:',Son.__module__)
  #实例类型
  print('实例类型:',Son().__class__)

运行效果如下:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
这是构造函数,son
类型帮助信息: A simple example class
类型名称: Son
类型所继承的基类: (<class '__main__.Father'>,)
类型字典: {'__module__': '__main__', 'sayHello': <function Son.sayHello at 0x010194F8>, '__doc__': 'A simple example class', '__init__': <function Son.__init__ at 0x010194B0>, 'i': 12345}
类型所在模块: __main__
这是构造函数,son
实例类型: <class '__main__.Son'>
>>>

Python支持多重继承

首先第一点,你会发现Class的定义中有一个括号,这是体现继承的地方。 Java用extends,C#、C++用冒号(:),Python则用括号了。从括号中包含着两个值,聪明的你一定可以发现:Python支持多重继承;

__init__是Class中的构造函数

第二点,__init__是Class中的构造函数,两种不同形式的构造函数体现了Python支持函数重载。在构造函数中,有一个特别的参数self,其含义与我们在Java和C#中常见的this是一样的。在这里需要强调一点:在Class中定义的方法实质上也是function,但是在方法定义的时候必须包含self这个参数,而且必须将self这个参数放在第一位;

python成员变量

第三点,在Python中,你并不需要显式的声明Class的Data Members,而是在赋值的时候,被赋值的变量就相应成为了Class的Data Memebers,正如代码中的x和y。不仅你不需要显式的声明Data Members,更加特别的,你甚至可以通过del方法将Class中的Data Memebers给删掉。当我第一次看到这样的特性的时候,着实吃了一惊。毕竟OO的第一条就是封装了,但是这样的特性是不是破坏了封装的特性呢?

python方法二义性问题

第四点,由于Python支持多重继承,因此就有可能出现方法二义性问题[1]。然而由于Python遵循深度优先的搜寻法则,很好地避免了方法二义性的问题。例如在以上的代码中,MyClass同时继承于BaseClassA和BaseClassB,假设MyClass调用一个叫derivedMethod方法,derivedMethod同时定义在BaseClassA和BaseClassB中,且Signature也完全相同,那么BaseClassA中的方法将被调用。如果BaseClassA中并没有定义derivedMethod,而是BaseClassA的父类定义了这个方法的话,将会是BaseClassA的父类中derivedMethod被调用。总之,继承方法搜索的路径是先从左到右,在选定了一个BaseClass之后,将会一直沿着该BaseClass的继承结构进行搜索,直至最顶端,然后再到另外一个一个BaseClass。

就先说着这么多了,对于Python中OO的特性将会在以后的Post中有进一步的讲述。

方法二义性:由于一个类同时继承于两个或者多个父类,而在这些父类当中存在着signature完全相同的方法,那么编译器将无法判断子类将继承哪个父类中的方法,从而导致方法二义性问题。

希望本文所述对大家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
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version