第五章:类
本章讲述了类在python中的使用方式。
9-3
class User():
attributes = {}
def __init__(self, first_name, last_name, **kwargus):
self.attributes['first_name'] = first_name
self.attributes['last_name'] = last_name
for key, item in kwargus.items():
self.attributes[key] = item
def describe_user(self):
for key, item in self.attributes.items():
print(key + '=' + item)
def greet_user(self):
print(self.attributes['first_name'] + ' ' + self.attributes['last_name'] + ', hello?')
a = []
for i in range(0,10):
x = User('A', 'a', something='blablabla')
x.describe_user()
x.greet_user()
a.append(x)
9-7
class User():
attributes = {}
def __init__(self, first_name, last_name, **kwargs):
self.attributes['first_name'] = first_name
self.attributes['last_name'] = last_name
for key, item in kwargs.items():
self.attributes[key] = item
def describe_user(self):
for key, item in self.attributes.items():
print(key + '=' + item)
def greet_user(self):
print(self.attributes['first_name'] + ' ' + self.attributes['last_name'] + ', hello?')
class Admin(User):
def __init__(self, first_name, last_name, privileges, **kwargs):
super().__init__(first_name, last_name)
self.privilege = privileges
for key, item in kwargs.items():
self.attributes[key] = item
def show_privileges(self):
for i in self.privilege:
print(i)
a = Admin('A', 'a', ['sudo', 'sud'])
a.show_privileges()
第十章:文件和异常
本章涉及到了文件IO操作以及异常处理。
10-1
filename = 'learning_python.txt'
with open(filename) as file_input:
a = file_input.readlines()
for i in a:
print(i.replace('python', 'C'))
10-6
try:
a = int(input('Please input a:'))
b = int(input('Please input b:'))
print('a+b=' + str(a + b))
except ValueError:
print('Please input integer instead of string')