python学习笔记------类的魔术方法与format
程序员文章站
2024-03-15 14:33:05
...
类的魔术方法
class OpenFile(object):
def __init__(self, filename, mode):
print("file is opening.......")
self.f = open(filename, mode)
def closed(self):
return self.f.closed
def __del__(self):
# del f1
# 程序执行结束....
self.f.close()
print("file is deleteing.....", self.f.closed)
f = OpenFile('/etc/passwd', 'r')
print(f.closed())
# del f
# print(f.closed())
file is opening.......
False
file is deleteing..... True
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
print("student is create")
def __str__(self):
return "Student:<%s,%s,%s>" %(self.name, self.age, self.score)
def __del__(self):
print("student is delete")
s1 = Student("westos", 19, 100)
print(s1)
student is create
Student:<westos,19,100>
student is delete
私有属性和变量
以双下划线开头的属性名或者方法名,外部是不可以访问的;
子类也不能直接使用父类的私有属性和私有方法;
eg:
# 子类也不能直接使用父类的私有属性和私有方法;
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
# 以双下划线开头的属性名或者方法名, 外部是不可以访问的;
self.__score = score
def set_score(self, value):
if 0<=value<=150:
self.__score = value
def __get_level(self):
if 90<self.__score<=100:
return "%s,%s,A" %(self.name,self.age)
elif 80<self.__score<=90:
return "%s,%s,B" %(self.name,self.age)
else:
return "%s,%s,C" %(self.name,self.age)
class MathStudent(Student):
def get_score(self):
print(self.__score)
s1 = Student("westos", 18, 100)
print(s1.name)
s2 = MathStudent("helo",10,90)
# print(s2.__score)
# s1.__get_level()
# print(s1.__score)
s1.name = "fentiao"
print(s1.name)
s1.score = 150
print(s1.score)
类的多继承算法
class D:
# pass
def test(self):
print("D test")
class C(D):
pass
# def test(self):
# print("C test")
class B(D):
pass
# def test(self):
# print("B test")
class A(B,C):
pass
# def test(self):
# print("A test")
a = A()
a.test()
format
自定义字符串的格式化
# format() 函数和字符串方法使得一个对象能支持自定义的格式化;
# 为了自定义字符串的格式化,我们需要在类上面定义 __format__()方法:
formats = {
'ymd':"{d.year}-{d.month}-{d.day}",
'dmy':"{d.day}/{d.month}/{d.year}"
}
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_spec): # 'dmy'
if not format_spec:
format_spec = 'ymd'
fmt = formats[format_spec]
return fmt.format(d=self)
d = Date('2018', '5', '20')
print(format(d, 'ymd')) # 2018-5-20
print(format(d, 'dmy')) # 20/5/2018
print(format(d)) # 2018-5-20
format格式转换:
字符传format方法的使用
format是python2.6新增的一个格式化字符串的方法,
相对于老版的%格式方法,它有很多优点。
1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型
2.单个参数可以多次输出,参数顺序可以不相同
3.填充方式十分灵活,对齐方式十分强大
4.官方推荐用的方式,%方式将会在后面的版本被淘汰
# 1.通过位置来填充字符串
print("hello %s" % ('world'))
# print("hello %s" %((1,2,3)))
print("hello {0}".format((1, 2, 3, 4)))
print("hello {0} {1} {0} {1}".format((1, 2, 3, 4), "python"))
print("hello {0:.3f}".format(1.8989))
# 2.通过key来填充
print("max:{max} min:{min}".format(min=10, max=100))
# 3.通过下标/index填充
point = (3,4)
print("x:{0[0]}, y:{0[1]}".format(point))
# 4.通过字典的key
d = {'max':100.7849758475976, 'min':10.4756895769857985}
print("max:{max:.2f} min:{min:.3f}".format(**d))
# 5. oop对象进行操作
class Book(object):
def __init__(self, name, author, state, bookIndex):
self.name = name
self.author = author
# 0:借出 1:未借出
self.state = state
self.bookIndex = bookIndex
# 打印对象时自动调用;str(对象)
def __str__(self):
return "书名:{0.name} 状态:{0.state}".format(self)
# return "书名:{d.name} 状态:{d.state}".format(d=self)
b = Book("java", 'aa', 1, 'Index')
print(b)
hello world
hello (1, 2, 3, 4)
hello (1, 2, 3, 4) python (1, 2, 3, 4) python
hello 1.899
max:100 min:10
x:3, y:4
max:100.78 min:10.476
书名:java 状态:1
上一篇: 微信模板消息开发总结——7.26
下一篇: SQL FORMAT() 函数