python的类

本文展示了如何在Python中创建一个User类,包含姓名、年龄等属性及描述、问候和更新年龄的方法。同时,创建了一个Student类,继承自User类,增加了学校和年级属性,以及上学方法。通过示例展示了如何初始化实例并调用这些方法。
摘要由CSDN通过智能技术生成

创建一个简单的类

"""用户类,初始化实例时必须包含用户姓名、年龄属性,还可以按照需要新增其它属性。"""
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的语法稍有不同。

python3python2.7
定义Class User():Class User(object):
继承的initsuper().__init__()super(Student,self).__init__
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值