python类

一、类

1.类的定义

类是用class定义的,里面有一些重要的东西,几乎是必须的,来看看是什么吧
类的定义:

class classname(object):
	def __init__(self, ...):
		...
	...

我们现在来定义一个学生类,有sid、name、age、country等特性:

class Student():
	def __init__(self, sid, name, age, country = None, others = None):
		self.sid = sid
		self.name = name
		self.age = age
		self.country = country
		self.others = others

初始化完了,现在该弄一些方法了

2.类的成员方法

我们接着后面的写,定义方法和函数一模一样,只不过必须有个参数self而已:

	def sreturn(self, sid = False, name = False, age = False, country = False, others = False):
		if sid == True:
			return self.sid
		if name == True:
			return self.name
		if age == True:
			return self.age
		if country == True:
			return self.country
		if others == True:
			return self.others
		return self.sid, self.name, self.age, self.country, self.others

3.类的成员调用

类定义好了,下面该调用了:

stu1 = Student(32, "QQ", 9, others = "四年级") #内部参数是__init__内除self的参数
print(stu1.sreturn()) #调用类中函数
#-----------------------------------------
#结果:(32, "QQ", 9, None, "四年级")

把stu1变成Student类的实例

4.类的继承

那如果还要加上民族,怎么办?假设汉族人统一用Student类,而其他民族就要用另一个了,继承一下Student就行了:

class Ostudent(Student): #所有类默认继承object
	def __init__(self, sid, name, age, minzu, country = None, others = None):
		super().__init__(sid, name, age, country = None, others = None #用父类的初始化方法
		self.minzu = minzu
	...#其他相同,只不过要多加一个民族

5.类的静态方法和类方法

静态方法不是绑定在实例上,而是绑定在类上

class Animal():
	name = "动物"
	
	@staticmethod
	def play(): #注意:这里没有self
		print("正在玩")

Animal.play() #不需要实例化,因为是静态方法

上面是静态方法的定义方法,需要在静态方法前加上一个装饰器@staticmethod,我们在此不扩展,作为一个了解即可

类方法:

class Animal():
	name = "动物"
	
	@classmethod
	def play(cls): #里面有一个参数,相当于self,但不要写成self,否则调用的不是外部非__init__的name
		print(cls.name, "正在玩")

以上就是类的一些定义及调用方法了,更多请见:
https://www.runoob.com/python3/python3-class.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值