一点Python总结(3)

类属性 就是给类定义的属性
通常用来记录与这个类相关的特征,并不会

用于记录具体对象的特征

向上查找机制:

类方法:

@classmethod
def 类方法名(cls):

通过类名可以直接调用

定义静态方法

@staticmethod
def 静态方法名():

不需要访问实例属性和类属性可以创建静态

方法
可以不用创建类的对象就可以直接通过类名

调用

综合案例

class Game(object):
    top_score=0
    def __init__(self,player_name):
        self.player_name=player_name
    @staticmethod
    def show_help():
        print("帮助信息")
    @classmethod
    def show_top_score(cls):
        print("最高分%d" % cls.top_score)
    def start_game(self):
        print("%s游戏开始了。。。" %self.player_name)

Game.show_help()
Game.show_top_score()
game=Game("小明")
game.start_game()

单例设计模式
目的是让类创建的对象在系统中只有唯一的

一个实例
每一次执行返回的底线,内存地址是相同的

__new__方法
为对象分配内存空间,把内存地址返回给初

始化方法

模块
每一个以py结尾的源文件都是一个模块

导入
import 模块名 as 别名

调用:
模块名.属性/方法/类

从某一模块中导入部分工具
from 模块名 import 工具名

导入之后不需要.的方式,可以直接使用属性/方法/类

__name__属性

文件操作
open read write close

try:
    file=open("index")
    text=file.read()
    print(text)
except Exception as error:
    print("%s" %error)
finally:
    file.close() 

循环读取每一行

file=open("index")
while True:
    text=file.readline()
    if not text:
        break
    print(text,end="")
file.close()

读取每一行写入另一文件

file=open("index")
file1=open("index1","w")
while True:
    text=file.readline()
    if not text:
        break
    file1.write(text)
file.close()
file1.close()

正常写入

file=open("index")
file1=open("index1","w")
text=file.read()
file1.write(text)
file.close()
file1.close()

eval基础使用
将字符串当成有效的表达式来求值并返回计算结果

注意:不要使用eval直接转换input的结果

案例

input_str=input("请输入算术题:")
print(eval(input_str))

控制台:
请输入算术题:(1+2)*5
15

猜你喜欢

转载自blog.csdn.net/weixin_42481081/article/details/83066656