美文网首页
property、classmethod、staticmetho

property、classmethod、staticmetho

作者: Yanl__ | 来源:发表于2019-08-26 13:20 被阅读0次
  • 属性方法
  • 类方法
  • 静态方法

property

内置装饰器函数,只能在面向对象中使用

  • 能将一个方法伪装成一个属性
# 未使用property装饰器函数
from math import pi
class Circle:
    def __init__(self, r):
        self.r = r

    def perimeter(self):
        return 2*pi*self.r

    def area(self):
        return self.r**2*pi

c1 = Circle(5)
print(c1.perimeter())
# 使用类property装饰器函数
from math import pi
class Circle:
    def __init__(self, r):
        self.r = r

    @property
    def perimeter(self):
        return 2*pi*self.r

    @property
    def area(self):
        return self.r**2*pi

c1 = Circle(5)
print(c1.perimeter)   # 将方法伪装成了属性
  • 通过property实现属性的修改
class Goods:
    discount = 0.8
    def __init__(self, name, price):
        self.name = name
        self.__price = price

    @property
    def price(self):
        return self.__price * Goods.discount

apple = Goods('苹果', 5)
print(apple.price)
  • 通过property实现属性的删除
class Person:
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):  # 1 
        return self.__name

    @name.deleter    # 2
    def name(self):  # 3   1,2,3 三处名称应该一样
        del self.__name

wang = Person('王力宏')
print(wang.name) # 能够输出name
del wang.name   # 删除了__name属性
print(wang.name)  # 报错

classmethod

把一个方法 变成一个类中的方法,这个方法就可以直接被类调用,不需要依托任何对象

class Goods:
    __discount = 0.8
    def __init__(self, name, price):
        self.name = name
        self.__price = price

    @property
    def price(self):
        return self.__price * Goods.__discount

    @classmethod  # 把一个方法 变成一个类中的方法,这个方法就可以直接被类调用,不需要依托任何对象
    def change_discount(cls, new_discount):  # 修改折扣
        cls.__discount = new_discount


apple = Goods('苹果', 5)
print(apple.price)
Goods.change_discount(0.5)  # 直接被类调用,不用依托任何对象
print(apple.price)

staticmethod

在完全面向对象的程序中,如果一个函数,即和对象没有关系,也和类没有关系,那么就用staticmethod将这个函数变成一个静态方法

class Login:
    def __init__(self, name, pwd):
        self.name = name
        self.pwd = pwd

    def login(self):
        pass

    @staticmethod  # 静态方法
    def get_usr_pwd():
        usr = input('username:')
        pwd = input('password:')
        Login(usr, pwd)

Login.get_usr_pwd()

相关文章

网友评论

      本文标题:property、classmethod、staticmetho

      本文链接:https://www.haomeiwen.com/subject/rkmrectx.html