Python-类

类的形式

class Student:
	name = 'who'#类属性 静态变量被所有类对象共享
	def __init__(self,age,city)::#构造函数 这里面的age和city就是每个类对象独有的参数 
		self.age = age
		self.__city = city#加了两个下划线__表示私有变量
	def fun(self):#实例方法
		print('实例方法',self.age)
	@classmethod
	def eat(cls):#类方法
		print('%s在吃饭',cls.name)#在类方法里不能用self 只能用cls
	@staticmethod
	def method():#这是一个静态方法
		print('方法')
stu = Student()
	

实例方法 静态方法 类方法的区别

实例方法

def fun(self):#实例方法

必须含有self 在调用时会自动把stu类对象最为参数传入

类方法

@classmethod
def fun(cls):#类方法

必须含有cls 在调用时会自动把Student类作为参数传入
cls.num_inst可以获取这个类有多少个对象

静态方法

@staticmethod
def fun():#静态方法

没有参数

动态绑定属性和方法


class Student:
	def __init__(self,name,age):
		self.name = name#这些属性都是类对象拥有的
		self.age = age
stu1 = Student('张三',1)
stu2 = Student('李四',2)

# 动态绑定属性
stu1.gender = '女'#这是stu1独有的 stu2没有
print(stu2.gender)#这样就会报错
# 动态绑定方法
def show():
	print('动态绑定的方法')
stu1.show = show
stu1.show()
	

继承

__init__构造器

前面的__表示是私有

__init__ 第一个参数必须为self 后续参数自定义
class A:
	def __init__(self,x,y,z):
		self.x = x
		self.y = y
		self.z = z
a = A(1,2,3)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值