绝知此事要躬行
这是我自己的试错文档,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。类属性需要写在方法外