创建一个简单的类
"""用户类,初始化实例时必须包含用户姓名、年龄属性,还可以按照需要新增其它属性。"""
class User():
def __init__(self,name,age,**user_info):
self.name = name
self.age = age
self.other_info = {}
for key,value in user_info.items():
self.other_info[key]=value
def describe(self):
print('name:'+self.name)
print('age:'+str(self.age))
for key,value in self.other_info.items():
print(key+':'+value)
def greet(self):
print('hello,my name is '+self.name.title())
print('what\'s your name?')
def update_age(self,new_age):
if new_age < int(self.age):
print('be serious,you can\'t grow younger!')
elif new_age > 200:
print('we adout that this is not you real age.')
else:
self.age = new_age
使用上面创建的User类
"""初始化一个user1实例,并尝试调用其中的方法"""
import class_user
user1 = class_user.User('zxx','50',sex='female',cop='dm')
user1.describe()
user1.greet()
user1.update_age(25)
user1.describe()
类继承
"""Student类继承了User类,多了school和level属性"""
import class_user
class Student(class_user.User):
def __init__(self,name,age,school,level,**user_info):
super().__init__(name,age,**user_info)
self.school = school
self.level = level
def goto_school(self,day):
if day.lower() == 'saturday' or day.lower() == 'sunday':
print('today is '+day+',i don\'t need to go to school')
elif day.lower() in ['monday','tuesday','wednesday','thursday','monday']:
print('today is '+day+',i have to go to school')
else:
print(day+' is illegal')
def describe(self):
super().describe()
print('school:'+self.school)
print('level:'+self.level)
使用Student类:
import class_student
student1 = class_student.Student('zxx','12','xxschool','grade 1',sex='female')
student1.describe()
student1.greet()
student1.goto_school('monday')
python3和python2.7在类上的语法差别
以上语法都是适用于python3的,python2.7的语法稍有不同。
python3 | python2.7 | |
---|---|---|
定义 | Class User(): | Class User(object): |
继承的init | super().__init__() | super(Student,self).__init__ |