Python面向对象之静态方法、静态方法与类方法

  • 静态属性:

类调用函数属性时,需要先将类实例化,再将实例作为函数属性传入;类的实例调用函数属性时需要在后面加括号。

 

class Building:
    def __init__(self, name, owner, width, length):
        self.name = name
        self.owner = owner
        self.width = width
        self.length = length

    def a(self):
        print('a')

    def cal_area(self):
        return self.length * self.width


B1 = Building('艺术楼', '艺术学院', 100, 100)
print(Building.cal_area)
#   <function Building.cal_area at 0x107f11f28>
print(Building.cal_area(B1))
#   10000
print(B1.cal_area())
#   10000

类中提供了@property关键字,@property可以看成是一个装饰器。因此,类的实例可以直接通过点调用函数属性而不需加括号就能执行。此时,该函数属性就可称为静态属性

 

class Building:
    def __init__(self, name, owner, width, length):
        self.name = name
        self.owner = owner
        self.width = width
        self.length = length

    def a(self):
        print('a')

    @property
    def cal_area(self):
        return self.length * self.width


B1 = Building('艺术楼', '艺术学院', 100, 100)
print(Building.cal_area) 
#   <function Building.cal_area at 0x107f11f28>
print(B1.cal_area)
#   10000
print(Building.cal_area(B1))
#   TypeError: 'property' object is not callable

 

  • 类方法

类的方法前加@classmethod,不需要实例化,直接调用类的该方法。可以访问类的数据属性,但是不可以访问对象的数据属性。

 

class Building:
    tag = 'nice'

    def __init__(self, name, owner, width, length):
        self.name = name
        self.owner = owner
        self.width = width
        self.length = length

    @classmethod
    def is_beauty(cls):
        print(cls)
        print('这个房间很%s' % (cls.tag))
        # print(cls.name)   #   不能访问实例对行的数据属性,报错:   AttributeError: type object 'Building' has no attribute 'name'

B1 = Building('艺术楼', '艺术学院', 100, 100)
Building.is_beauty()
#   <class '__main__.Building'>
#   这个房间很nice
B1.is_beauty()
#   <class '__main__.Building'>
#   这个房间很nice

 

  • 静态方法

类的方法前加@staticmethod,该方法均可被实例和类调用,但不能访问类属性以及实例属性,仅仅当做工具包使用。

 

class Building:
    tag = 'nice'

    def __init__(self, name, owner, width, length):
        self.name = name
        self.owner = owner
        self.width = width
        self.length = length

    @staticmethod
    def is_static_method(a, b, c):
        print(a, b, c)


B1 = Building('艺术楼', '艺术学院', 100, 100)
B1.is_static_method(1, 2, 3)
#   1 2 3
Building.is_static_method(1, 2, 3)
#   1 2 3

 

posted @ 2019-02-20 20:59  米兰的小铁匠_feng  阅读(210)  评论(0)    收藏  举报