纸上得来终觉浅

绝知此事要躬行

这是我自己的试错文档,Python学习中会遇到一些问题,有些小问题不行直接百度,不如自己直接写来试试

试错代码

import random
#
#
class animal:
     def __init__(self,type):
         self.type = type
         weight =123

         # if self.type == 'taiger':
             # weight =

 test= animal('2333')

#测试random.choice可同时作用列表或元祖。结果ok
 test1 = [1,2]
 test2 = (1,2)
 print(random.choice(test2))

#尝试在不定参内传入多个类,结果ok
 class test_num:
     def __init__(self,a):
         self.a = a

 class  forest:
     def __init__(self,count,*monster):
         print(type(monster))
         for i in monster:
             print(i)

 test2 = forest(1,test_num(1).a,test_num(2).a)

#测试类属性和实例属性
#1.类熟悉必须init或其他方法外
#2.实例属性必须以self来承接
#3.类属性可通过对象和类名调用
#4.实例属性不可通过类名调用
#5.类属性不可在实例后更改
 class soldier:
     soldier_name = '普通人'
     soldier_price = 100
     def __init__(self):
         self.soldier_hp_max = 100 - self.soldier_price
         self.soldier_hp_now = 100

 test = soldier()
 print(test.soldier_)

#测试空列表长度是否为0,很明显是的
dic1 = [] 
print(len(dic1))

#测试字符串是否能相等
 if 'sed' == 'sed':
     print('1')

#测试os文件遍历
#a是当前目录,b是文件列表,c是文件列表
import os
for a,b,c in os.walk(r'.\test8_class'):
    print(a,b,c,'\n')

#字符串不可以通过索引直接修改,可以用replace实现
 a = '12345'
 a[2] = '2'

#关于 string 的 replace 方法,需要注意 replace 不会改变原 string 的内容。
#str.replace 实际返回的是一个修改了匹配文案的str
 a= '12345'
 a.replace('1','2')
 print(a)

#r+模式,r+模式从开始读,读完光标在最后,所以写的表现形式看起来是追加,而不是覆盖
 with open('test_file.txt','r+',encoding='utf-8') as text:
     a1 = text.readlines()
     text.writelines(a1)
     print(a1)

报错处理

在这里插入图片描述
AttributeError:
解释:找不到对象里的这个属性。原因是代码内weight既不是实例属性也不是类属性。
实例属性需要self。类属性需要写在方法外

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值