Loading

Python 的 类方法 静态方法 和 proprety

@classmethod

被classmethod装饰的方法称为类方法,他是属于类的,而不是实例化对象的。它的第一个参数不是代表实例化对象的 self 而是类表示类本身的 cls

也就是说他的调用可以直接使用类调用,它也可以直接的修改类属性,总而言之它是属于类的或者操作是对类而言的。它的调用不需要实例化。


# 例子
class Test(object):
    count = 0

    @classmethod
    def set_count(cls, value):
        if isinstance(value, int) and 0 < value < 10:
            cls.count = value

    @classmethod
    def get_count(cls):
        return cls.count


Test.set_count(5)
print(Test.get_count())

@staticmethod

静态方法, 相当于定义在类内部的普通方法,只是需要通过类或对象来进行调用。他不需要传入selfcls,也就是说它的第一个变量没有特殊的含义。

原则上,他也不能使用任何类或者实例的属性和方法。

静态方法原则上是属于类的,但是实际上和类并没有太多的关系,只是封装在类的内部仅此而已。将它封装在类中,依托类的命名空间来管理,更有利于维护代码。

# 例子
class Test(object):

    @staticmethod
    def sum(num1, num2):  # 第一个参数不是 self 或 cls
        return num1 + num2


print(Test.sum(1, 4))  # 也不需要实例化 但是实例化对象也可以调用静态方法

@property

以装饰器形式使用property,被装饰得方法将成为只读的方法,可以像访问属性一样访问方法,得到的值为方法的返回值。需要改写这个属性的话需要用装饰器@属性名.setter装饰同名方法。


class Test(object):
    def __init__(self):
        self._count = 2

    @property  # 允许以属性的方式执行方法。在外的表现为属性,本质上是一个方法。
    def count(self):
        return self._count

    @count.setter  # 定义方法(属性)的设置行为,<这样能检查传入的值 是否是期望的,在这里做检查。>
    def count(self, value):
        """ 如果没有这个方法,那么属性是只读的,也就是不允许赋值 """
        if isinstance(value, int):
            self._count = value


@count.deleter  # 定义方法(属性)的删除行为。


""" 如果没有定义这个方法,那么属性是不允许删除的 """


def count(self):
    self._count = 0


a = Test()

a.count = 100
print(a.count)
del a.count
print(a.count)

以函数的方式使用property


class Test(object):
    def __init__(self):
        self._count = 2

    def get_count(self):
        return self._count

    def set_count(self, value):
        if isinstance(value, int):
            self._count = value

    def del_count(self):
        self._count = 0

    count = property(fset=set_count,
                     fget=get_count,
                     fdel=del_count,
                     doc="docs for count."
                     )


a = Test()

a.count = 100
print(a.count)
del a.count
print(a.count)
posted @ 2020-06-18 18:19  StKali  阅读(313)  评论(0编辑  收藏  举报