欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

property classmethod staticmethod的用法

发布时间:2025/6/16 编程问答 71 豆豆
生活随笔 收集整理的这篇文章主要介绍了 property classmethod staticmethod的用法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一:property的用法

1,@property 能够将一个方法伪装成一个属性,它并不会让你的代码有什么逻辑上的提高,只是从调用者的角度上换了一种方式,使之看起来更合理。调用方法从原来的的对象名.方法名(),变成了对象名.方法名。

class Person:def __init__(self,name,weight,height):self.name = nameself.__height = heightself.__weight = weight@propertydef bmi(self):return self.__weight / self.__height ** 2 p = Person('ads',70,1.75) print(p.bmi) View Code

2,方法伪装成的属性的修改

class Person:def __init__(self,n):self.__name = n # 私有的属性了 @propertydef name(self):return self.__name@name.setter # 重要程度 ***def name(self,new_name):if type(new_name) is str:self.__name = new_nameelse:print('您提供的姓名数据类型不合法')p = Person('alex') print(p.name) #def name(self): p.name = 'alex_sb' #def name(self,new_name): print(p.name) #def name(self): View Code

3,方法伪装成的属性的删除

class Person:def __init__(self,n):self.__name = n # 私有的属性了@property # 重要程度 ****def name(self):return self.__name@name.deleterdef name(self):del self.__namep = Person('alex') print(p.name) del p.name View Code

ps:

@property --> func 将方法伪装成属性,只观看的事儿

@func.setter --> func 对伪装的属性进行赋值的时候调用这个方法 一般情况下用来做修改

@func.deleter --> func 在执行del 对象.func的时候调用这个方法 一般情况下用来做删除 基本不用

二:classmethod的用法

1,@classmethod ,类方法,可以直接被类调用,不需要默认传对象参数,只需要传一个类参数就可以了。

class Goods:__discount = 0.8def __init__(self,name,origin_price):self.name = nameself.__price = origin_price@propertydef price(self):return self.__price * Goods.__discount@classmethoddef change_discount(cls,new_discount):cls.__discount = new_discountGoods.change_discount(1) # 不依赖对象的方法 就应该定义成类方法 类方法可以任意的操作类中的静态变量 # 如果要改变折扣 是全场的事情 不牵扯到一个具体的物品 所以不应该使用对象来调用这个方法 apple = Goods('apple',5) banana = Goods('banana',8) print(apple.price) print(banana.price) View Code

三:staticmethod的用法

当一个方法要使用对象的属性时 就是用普通的方法

当一个方法要使用类中的静态属性时 就是用类方法

当一个方法要既不使用对象的属性也不使用类中的静态属性时,就可以使用staticmethod静态方法

class Student:def __init__(self,name):pass@staticmethoddef login(a):# login就是一个类中的静态方法 静态方法没有默认参数 就当成普通的函数使用即可user = input('user :')if user == 'alex':print('success')else:print('faild')Student.login(1) View Code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/leiwei123/p/8874366.html

总结

以上是生活随笔为你收集整理的property classmethod staticmethod的用法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。