分享

Python3 【类】类基础知识

 网摘文苑 2022-11-16 发布于新疆

创建类

类的创建以class开头,之后跟着名字,并以冒号结尾。(建议类的名字使用驼峰式记法:一大些字母开头,并且随后紧跟的任意一个单词都要以大写字母开头)。注意Python中不需要括号,直接通过缩进就可以管理。
下面创建一个最简单的类

class MyFirstClass:  
    class_suite=0

使用命令pyhton -i firsrt_class.py运行这段代码,-i 的意思是运行这段代码之后,抛向交互解释器。

>>> a=MyFirstClass()
>>> print(a)
<__main__.MyFirstClass object at 0x7f70900f16d8>
>>> print(a.class_suite)
0

对一个已经实例化了的类,可以通过点运算符赋予任意属性。例如接着上面的运行。

>>> a.x=5
>>> a.y=10
>>> print(a.x,a.y)
5 10

定义方法

所谓的方法,其实就是函数,只不过是出现在类中的函数而已。python中方法的定义和函数相同,以关键字def开头。注意,所有方法都必须有一个参数,那就是self。 self参数,是对调用这个方法的对象的一个引用。

class Apple:
    color=10
    weight=12
    def reset(self):
        self.color=0
        self.weight=0
>>> apple=Apple()
>>> print(apple.color,apple.weight)
10 12
>>> apple.reset()
>>> print(apple.color,apple.weight)
0 0

对象的初始化

大部分面向对象语言都有一个构造函数的特殊方法。但是Python不同,Python有一个构造函数和一个初始化函数,正常情况下,构造函数很少使用。Python的初始化方法和其他方法没有什么不同。只不过是有一个特殊的名字“__init__”,开始和结尾的双下划线表示这是一个特殊的方法。对自己定义函数,不要使用双下划线。
例如:

class Apple:
    def __init__(self, color, weight):
        self.color=color
        self.weight=weight
>>> apple=Apple('red',100)
>>> print(apple.color,apple.weight)
red 100

定义的这个函数就是用于初始化的函数,通过运行可以看出他的使用方式。其实和其他语言里面的构造函数是很相似的。

模块和包

当创建的类很多的时候,为了方便管理,不宜全部放在一个文件中,这时就会用到模块。模块就是非常简单的Python文件,单个Python文件就是一个模块,两个文件就是两个模块。import函数就是用来导入模块或者从模块中导入特定的类或者函数。
包就是放到一个文件夹里的模块的集合。包的名字就是文件夹的名字。我们需要做的只是告诉Python这个文件夹是一个包,并且把一个名为__init__.py的文件(通常是空的)放到这个文件夹里。如果忘记创建这个文件,就没法从这个文件夹里导入那些模块
下面是一个文件关系的例子,每一个包都应该包含一个 __init__文件。
在这里插入图片描述

管理模块

包之间导入模块或者类的时候,要注意语法。Python3中,导入模块有两种方式:绝对导入和相对导入。

绝对导入

绝对导入需要指明这个模块、函数的完整路径。以上面给出的文件路径为例,如果我们需要访问products模块里的Product类,可以使用下面的方法绝对导入:

import ecommerce.products
product = emomerce.products.Product()

或者

from ecommerce.products import Product
product = Product()

或者

from ecommerce import products
product = products.Product()

相对导入

当处理一个包里的相关模块时,详细指明完整路径是没有必要的。因为他们本身就在一个文件夹下。例如database.py和products.py是两个并列的的模块。例如,当前正在products这个模块下面工作,从database模块导入可以使用相对导入:
from .database import Database
如果需要访问上一级文件的内容,可以加两个点。这一点和linux下的文件路径操作是一样的。例如:
from ..contact.email import send_email

当导入模块的时候,模块里的所有代码都会被立即执行。如果模块里的是一个方法或者一个方法或者函数,就会创建这个函数,并且这个函数里的代码知道函数被调用的时候才会执行。通常,我们会写一个程序来让它做一些事情,但是当我们想要从另一个模块导入一些函数或者类,只要导入了它,那么被导入的模块里的所有代码就会立即执行。当我们只是想访问那个模块里的一些函数的时候,如果不小心,可能会把当前正在运行的程序终止掉。
为了解决这个问题,我们应该把启动代码放到一个函数里(通常写做main函数)

class MyClass :
	...def main():
	a=MyClass()
	print(a)if __name__ == '__main__':
	main()

每一个模块都有一个特殊的变量__name__,当导入这个模块的时候,这个变量指明了模块的名字。当导入这个模块的时候,这个变量指明了模块的名字。
注意
__name__是每一个模块内置的一个变量。一个模块的__name__的值取决于您如何应用模块。如果是导入一个模块,那么模块__name__ 的值是模块文件名,不带路径或者文件扩展名。直接运行模块的时候,name 的值将是'main'。这就意味着,当模块被直接运行的时候,将执行这个判断语句下面的程序,当模块被导入的时候,这个判断语句下的代码块不会被执行。这样就避免了每次已导入模块就执行模块里的所有运行程序。

访问权限

Python没有强制的权限限制,比如设置private,protected,public,这些Python都没有。
一个类里的所有方法和数学都是公共可以访问的。如果我们可以给一个属性或者方法加一个下划线的 前缀,“表明这是一个内部变量,直接访问它之前请三思”。但是这只是告诉编程者尽量不要访问,但是并不阻止访问。

#!/usr/bin/env python3# -*- coding: utf-8 -*-'''
Created on Thu Nov 22 21:14:50 2018

@author: zhao
'''import datetime

last_id=0class Note:
    '''Represent a note in the notebook.Match against a
    string in searches and store tags for each note.'''
    
    def __init__(self, memo, tags=''):
        '''initialize a note with memo and optional
        space-separated tags. Automatically set the note's
        creation date and a unique id.'''
        self.memo = memo
        self.tags = tags
        self.creation_date = datetime.date.today()
        global last_id
        last_id += 1
        self.id = last_id    
    def match(self,filter):
        '''Determine if this note matches the filter
        text. Return True if it matches,False otherwise.
        
        Search is case sensitive and matches both text and tags.'''
        return filter in self.memo or filter in self.tags        
class Notebook:
    '''Represent a collection of notes that can be tagged,
    modified, and searched.'''
    
    def __init__(self):
        '''initialize a notebook with an empty list.'''
        self.notes=[]
        
    def new_note(self, memo, tags=''):
        '''Create a new note and add it to the list.'''
        self.notes.append(Note(memo,tags))
    
    def modify_memo(self, note_id,memo):
        '''Find the note with the given id and change its
        memo to the given value'''
        self._find_note(note_id).memo = memo            
    def modify_tags(self, note_id, tags):
        '''Fiind the note with the given id and change its
        tags to the given value.'''
        for note in self.notes:
            if note.id == note_id:
                note.tags = tags                break
    
    def search(self, filter):
        '''Find all notes that match the given filter string.'''
        return [note for note in self.notes if note.match(filter)]
        
    def _find_note(self,note_id):
        '''locate the note with the given id.'''
        for note in self.notes:
            if note.id == note_id:
                return note        return Noneimport sysclass Menu:
    '''Display a memu and respond to choices when run.'''
    def __init__(self):
        self.notebook = Notebook() #attention
        self.choices = {
                '1' : self.show_notes,
                '2' : self.search_notes,
                '3' : self.add_note,
                '4' : self.modify_note,
                '5' : self.quit                }
    def display_menu(self):
        print('''
Notebook Menu

1.Show all Notes
2.search Notes
3.Add Note
4.Modify Note
5.Quite
''')
        
    def run(self):
        '''Display the menu and respond to choice.'''
        while True:
            self.display_menu()
            choice = input('Enter an option: ')
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print('{0} is not a valid choice'.format(choice))
    
    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes        for note in notes:
            print('{0}: {1}\{2}'.format(
                    note.id, note.tags, note.memo))
    def search_notes(self):
        filter = input('Search for: ')
        notes = self.notebook.search(filter)
        self.show_notes(notes)
        
    def add_note(self):
        memo = input('Enter a memo: ')
        self.notebook.new_note(memo)
        print('Your note has been adden.')
        
    def modify_note(self):
        id = input('Enter a note id: ')
        memo = input('Enter a memo: ')
        tags = input('Enter tags: ')
        if memo:
            self.notebook.modify_memo(id,memo)
        if tags:
            self.notebook.modify_tags(id,tags)
    
    def quit(self):
        print('Thank you for using your notebook today.')
        sys.exit(0)
    if __name__ == '__main__':
    Menu().run()  #pay attention to the way which uses the method

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多