""" 构造方法:__init__,用作实例对象的初始化,实例对象时默认调用 实例方法:默认第一个参数为self,只能被实例对象调用 类方法:由@classmethod来装饰的方法,默认第一个参数为cls,可以被类或则类对象调用 静态方法:由@staticmethod装饰的方法,没有默认参数,可以被类或则类的实例对象调用 属性方法:由@property装饰的方法,默认第一个为self,将方法当做属性来使用 """ class Demo(): school='高级中学' __num=1000 def __init__(self,name,grade,addr): #构造方法 self.name=name self.__grade=grade self.addr=addr def fun1(self): #实例方法,公有 print('类中公有fun1函数') def __fun2(self): #实例方法,私有 print('类中私有fun2函数') def fun3(self): self.fun1() #类内调用公有实例方法 self.__fun2() #类内调用私有实例方法 @classmethod def class_fun(cls): print('class_fun类中方法,装饰器@classmethod装饰的方法') @staticmethod def static_fun(): print('static_fun静态方法,装饰器@staticmethod装饰的方法') static_fun() @property def prop(self): print('pro属性方法,装饰器@property装饰的属性') d=Demo('王自强',100,20) d.fun1() #类外调用公有实例方法 d.prop #实例方法封装,把多个对象共同的功能封装为实例方法 class Match(): def __init__(self,x,y): self.x=x self.y=y def upper(self): self.y+=1 print("向上移动后的位置:{}".format(self.y)) return self.y def lower(self): self.y-=1 print("向下移动后的位置为:{}".format(self.y)) return self.y def right(self): self.x+=1 print('向右移动后的位置为:{}'.format(self.x)) return self.x def left(self): self.x-=1 print('向左移动后的位置为:{}'.format(self.x)) return self.x rabbit=Match(0,0) tutor=Match(0,0) rabbit.upper() rabbit.right() tutor.right() rabbit.right() rabbit.upper() rabbit.right() tutor.right() tutor.upper() print('比赛结束rabbit到达后的坐标为{},{}'.format(rabbit.x,rabbit.y)) print('比赛结束tutor到达后的坐标为{},{}'.format(tutor.x,tutor.y)) #用@property装饰器装饰的方法,就相当于把方法变成了类中的一个属性,属性名即方法名,使用和赋值就跟类中属性的操作一致 class Mobile(): def __init__(self,mobile,money,password): self.mobile=mobile self.__money=money self.__password=password @property def money(self): #get方法用@property装饰money属性,获取私有属性__money return self.__money @money.setter def money(self,m): #set方法用@xxx.setter装饰,修改私有属性__money secret=input('请输入密钥:') if secret==self.__password: if isinstance(m,int) or isinstance(m,float): if m>0 and m<self.__money: self.__money-=m else: print('支付失败') else: print('金额输入有误') else: print('密码验证失败') quit() Ant=Mobile('18912341928',90,'112233') print('查看{}账号余额为{}'.format(Ant.mobile,Ant.money)) #手机支付21元后的余额 Ant.money=21 print('手机支付后,{}账号余额为:{}'.format(Ant.mobile,Ant.money))
Python类和对象之--类的实例化方法封装和类的私有属性封装
最新推荐文章于 2022-11-20 14:07:09 发布
本文详细介绍了Python中的面向对象编程特性,包括构造方法`__init__`、实例方法、类方法(@classmethod)、静态方法(@staticmethod)和属性方法(@property)。通过实例展示了如何定义和调用这些方法,并利用`@property`装饰器实现属性的读取和设置。此外,还展示了如何封装实例方法,以及如何使用`@property`装饰器创建只读属性,确保数据的安全性。
摘要由CSDN通过智能技术生成