search
HomeBackend DevelopmentPython TutorialPython类的基础入门知识

复制代码 代码如下:

class Account(object):
"一个简单的类"
account_type="Basic"
def __init__(self,name,balance):
"初始化一个新的Account实例"
self.name=name
self.balance=balance
def deposit(self,amt):
"存款"
self.balance=self.balance+amt
def withdraw(self,amt):
"取款"
self.balance=self.balance-amt
def inquiry(self):
"返回当前余额"
return self.balance

其中,__init__函数就是Python中的构造函数。另外,balance这个变量是类实例的变量。
另外,在python中类中定义成员函数一般第一个参数总是self,表示自已的实例,与C++中的this指针差不多,不过C++中的this指针是隐函于其中并全局可见的,而在Python中却要作为参数传进去, 这是Python中定义类的另一个特点。
还有一个特点,在类的成员函数中,使用类中的另一个成员函数,前面必须要指定类名,如下:
复制代码 代码如下:

class Foo(object):
def bar(self):
print "bar!"
def spam(self):
bar(self) # 错误,引发NameError, 可以是:self.bar
Foo.bar(self) # 合法的

2.在类中声时静态方法并使用静态方法
要在类中使用静态方法,需在类成员函数前面加上@staticmethod标记符,以表示下面的成员函数是静态函数。使用静态方法的好处是,不需要定义实例即可使用这个方法:另外,多个实例共享此静态方法,如下: 
复制代码 代码如下:

class SimClass():
@staticmethod
def ShareStr():
print "This is a static Method"
SimClass.ShareStr() #使用静态函数

3.类方法:
类方法与普通的成员函数和静态函数有不同之处,在接触的语言中好像也没见过这种语义,看它的定义:
一个类方法就可以通过类或它的实例来调用的方法, 不管你是用类来调用这个方法还是类实例调用这个方法,该方法的第一个参数总是定义该方法的类对象。
记住:方法的第一个参数都是类对象而不是实例对象.
按照惯例,类方法的第一个形参被命名为 cls. 任何时候定义类方法都不是必须的(类方法能实现的功能都可以通过定义一个普通函数来实现,只要这个函数接受一个类对象做为参数就可以了).
定义类方法并使用类方法:
复制代码 代码如下:

class ABase(object):
@classmethod #类方法修饰符
def aclassmet(cls): print 'a class method for', cls.__name__
class ADeriv(ABase): pass
bInstance = ABase( )
dInstance = ADeriv( )
ABase.aclassmet( ) # prints: a class method for ABase
bInstance.aclassmet( ) # prints: a class method for ABase
ADeriv.aclassmet( ) # prints: a class method for ADeriv
dInstance.aclassmet( ) # prints: a class method for ADeriv

也就是说,类方法并不是必须的,使用普通函数也可以实现类方法的功能。
4.类的继承
在python中,继承一个类,就像这样:
class A(object) #继承object类
#.......
class B(A) #继承A类
#........
另外,python中支持多继承,对于多继承,找某个对应的函数,其python有相应的方法,如: 
复制代码 代码如下:

class D(oject): pass #D继承自object
class B(D): #B是D的子类
varB = 42
def method1(self):
print "Class B : method1"
class C(D): #C也是D的子类
varC = 37
def method1(self):
print "Class C : method1"
def method2(self):
print "Class C : method2"
class A(B,C): #A是B和C的子类
varA = 3.3
def method3(self):
print "Class A : method3"

如果我要调用A.method1() ,会出现什么结果?答案是ClassB:method1. 书上是只样介绍的:
当搜索在基类中定义的某个属性时,Python采用深度优先的原则、按照子类定义中的基类顺序进行搜索。**注意**(new-style类已经改变了这种行为)。上边例子中,如果访问 A.varB ,就会按照A-B-D-C-D这个顺序进行搜索,只要找到就停止搜索.若有多个基类定义同一属性的情况,则只使用第一个被找到属性值:
5.数据隐藏
在python中实现数据隐藏很简单,不需要在前面加什么关键字,只要把类变量名或成员函数前面加两个下划线即可实现数据隐藏的功能,这样,对于类的实例来说,其变量名和成员函数是不能使用的,对于其类的继承类来说,也是隐藏的,这样,其继承类可以定义其一模一样的变量名或成员函数名,而不会引起命名冲突。
复制代码 代码如下:

class A:
def __init__(self):
self.__X = 3 # self._A__X
class B(A):
def __init__(self):
A.__init__(self)
self.__X = 37 # self._B__X
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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),