Python静态方法和类方法

方法就是一个函数,它作为一个类属性而存在,可以使用如下方式进行声明、访问一个函数:

class Student(object):
      def __init__(self,sex):
          self.sex = sex
      
      def get_sex(self):
          return self.sex

print Student.get_sex
<unbound method Student.get_sex>

Python在告诉你,属性get_sex是类Student的一个未绑定的方法。这是什么意思

print print Student.get_sex()
Traceback (most recent call last):
  File "D:/project_11/SmartCleaner_python/home_application/__init__.py", line 13, in <module>
    print Student.get_sex()
TypeError: unbound method get_sex() must be called with Student instance as first argument (got nothing instead)

这样不能进行调用,因为它还没有绑定到Student类的任何实例对象上,它需要一个实例作为第一个参数传递进去(Python2必须是该类的实例,Python3中可以是任何东西),如下:

print Student.get_sex(Student('OK'))
OK

现在用一个实例对象作为它的第一个参数来调用,但是这种还是不最方便的,如果每次调用这个方法,不得不引用这个类,随着代码量的增加,如果忘记了哪个类是所需要的,会造成程序的混乱,所以长期看来这种方法是行不通的。
Python绑定了所有来自类Student的方法以及该类的任何一个实例方法,也就是以为着现在属性get_sex是Student的一个实例对象的绑定方法,这个方法的第一个参数就是该实例本身。

print Student('OK').get_sex
<bound method Student.get_sex of <__main__.Student object at 0x0000000003116898>
print Student('OK').get_sex()
OK

现在不需要提供任何参数给get_sex,因为它已经是绑定的,它的self参数会自动的设置给Pizza实例。

student = Student('OK').get_sex
print student()
OK

获取绑定的方法在哪个对象上

student = Student('OK').get_sex
print student.__self__
print student == student.__self__.get_sex
<__main__.Student object at 0x0000000003116898>
True

在Python3中,依附在类上的函数不再当作是未绑定的方法,二十把它当作一个简单函数,如果有必要它会绑定到一个对象身上去,原则依然和Python保持一致,但是模块更简洁:

lass Student(object):
      def __init__(self,sex):
          self.sex = sex
      
      def get_sex(self):
          return self.sex

print Student.get_sex
<__main__.Student object at 0x0000000003116898>
静态方法

静态方法是一类特殊的方法,有时可能需要写一个属于这个类的方法,但是这些代码完全不会使用到实例对象本身,例如:

class Student(object):
    @staticmethod
    def aver_age(x, y):
        return x + y

    def year(self):
        return self.aver_age(self.month, self.day)

这个例子中,如果把aver_age作为非静态方法同样可以运行,但是它要提供self参数,而这个参数在方法中根本不会被使用到。这里的@staticmethod装饰器可以给我们带来一些好处,Python不再需要为Student对象实例初始化一个绑定方法,绑定方法同样是对象,但是创建需要成本,而静态方法可以避免这些。

Student().year is Student().year
Student().aver_age is Student().aver_age
Student().aver_age is Student.aver_age
False
True
True

可读性更好的代码,看到@staticmethod我们就知道这个方法并不需要依赖对象本身的状态。
可以在子类中被覆盖,如果是把aver_age作为模块的顶层函数,那么继承自Student的子类就没法改变Student的aver_age了如果不覆盖year的话。

类方法

什么是类方法?类方法不是绑定到对象上,而是绑定在类上的方法。

class Student(object):
    score = 100

    @classmethod
    def get_score(cls):
        return cls.score

print Student.get_score
print Student().get_score
print Student().get_score is Student.get_score
print Student.get_score()

<bound method type.get_score of <class '__main__.Student'>>
<bound method type.get_score of <class '__main__.Student'>>
False
100

无论用哪种方式访问这个方法,它总是绑定到了这个类身上,它的第一个参数是这个类本身(类也是对象)
什么时候使用这种方法呢? 类方法通常在以下两种场景是非常有用的:

  • 工厂方法: 它用于创建类的实例,例如一些预处理。如果使用@staticmethod代替,那我们不得不硬编码Student类名在函数中,这使得任何继承Student的类都不能使用我们这个工厂方法给它自己用。
class Student(object):
  def __init__(self, age):
    self.age= age

  @classmethod
  def year_day(cls, year):
    return cls(year.get_cheese() + fridge.get_day())
  • 调用静态类:如果把一个静态放啊拆分多个静态方法,除非使用类方法,否则还是得硬编码类名。使用这种方式声明方法,Student类名永远都不会再被直接饮用,继承和方法覆盖都可以完美的工作。
class Student(object):
      def __init__(self,heigh,weigh):  
          self.heigh = heigh
          self.weigh = weigh
      @staticmethod
      def compute(heigh):
          return math.pi * (heigh ** 2)
     
      @classmethod
       def compute_value(cls,heigh,wegigh):
           return weigh * cls.compute(heugh)

      def get_value(self):
            return self.conpute_value(self.heigh, self.weigh)
  • 抽象方法
    抽象方法是定义在基类中的一种方法,它没有提供任何实现,类似于Java中接口(Interface)里面的方法。
    在Python中实现抽象方法最简单的方式:
class Student(object):
      def get_score(self):
          raise NotImplementedError

人格继承自Student的类必须覆盖实现方法get_score,否则会抛出异常。
这种抽象方法的实现有它的弊端,如果你写一个类继承Student,但是忘记实现get_score,异常只要在正在使用的时候才会抛出来。

>>> Student()
<__main__.Student object at 0x7fb747353d90>
>>> Student().get_score()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 3, in get_score
NotImplementedError

还有一种方式可以让错误更早的触发,使用Python提供的abc模块,对象被初始化之后就可以抛出异常:

import abc

class BaseStudent(obiect):
      __metaclass__ =  abc.ADCMeta

      @abc.abstractmethod
      def get_score(self):

"""Method that should do something."""

使用abc,当你尝试初始化BaseStudent或者任何子类的时候立马就会得到一个TypeError,而无需等到真正调用get_score的时候才会发现异常。

BaseStudent()
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class BaseStudent with abstract methods get_score
  • 混合静态方法、类方法、抽象方法

当开始构建类和继承结构时,混个使用这些装饰器的时候到了,所以这里列出了一些技巧,声明一个抽象的方法,不会固定方法的原型,这就是意味着虽然虽然必须实现它,但是可以用任何参数列表来实现:

import abc

class BaseStudent(obiect):
      __metaclass__ =  abc.ADCMeta

      @abc.abstractmethod
      def get_score(self):

""""Returns the score list."""

class Message(BaseStudent):
      def get_msg(self,add,with_sex=False):
          sex = Sex() if with_sex else None
          return self.get_msg + sex

这样是允许的因为Message满足BaseStudent对象所定义的接口需求。同样也可以使用一个类方法或静态方法进行实现:

import abc

class BaseStudent(object):
  __metaclass__ = abc.ABCMeta

  @abc.abstractmethod
  def get_score(self):

"""Returns the score list."""

class Obj(BasePizza):
  @staticmethod
  def get_msg():
    return None

这同样是正确的,因为它遵循抽象类BaseStudent设定的契约。事实上get_msg方法并不需要知道返回结果是什么,结果是实现细节,不是契约条件。
因此,不能强制抽象方法的实现是一个常规方法、或者是类方法还是静态 方法,也没什么可争论的。从Python3开始(在Python2中不能如所期待的的运行),在avstractmethod方法上面使用@staticmethod和@classmethod装饰器为可能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值