26、面向对象的内置函数、类方法和静态方法

一、面向对象中的内置函数

1、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.area)     # 圆的面积
print(c1.perimeter) # 圆的周长

2、name.setter:将被property装饰成的属性进行重命名

class Person:
    def __init__(self,name):
        self.__name = name
    @property
    def name(self):
        return self.__name + 'sb'
    @name.setter
    def name(self,new_name):
        self.__name = new_name

tiger = Person('泰哥')
print(tiger.name)
tiger.name = '全班'
print(tiger.name)

注意事项:@name.setter 中的name和上面返回作用的函数name还有下面修改的name的名字必须一致!

3、name.deleter  用于对伪装成对象属性的属性进行删除 

class Person:
    def __init__(self,name):
        self.__name = name
        self.price = 20
    @property                        #将方法伪装成属性
    def name(self):
        return self.__name
    @name.deleter                 #将伪装的属性删除
    def name(self):
        del self.__name
    @name.setter                    #重新对属性赋值
    def name(self,new_name):
        self.__name = new_name
brother2 = Person('二哥')
del Person.price
brother2.name = 'newName'
del brother2.name
print(brother2.name)

4、类方法:classmethod 把一个方法变成一个类中的方法,这个方法就直接可以被类调用,不需要依托任何对象。只有这个方法的操作只涉及静态属性的时候,就应该使用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)   # Goods.change_discount(Goods)
print(apple.price)          
当这个方法的操作只涉及静态属性的时候 就应该使用classmethod来装饰这个方法

二、面向对象中的类方法

  • 类方法和静态方法,都是类调用的。
  • 对象也可以调用类方法和静态方法,但是,一般推荐使用类名调用
  • 类方法中有一个默认cls ,代表这个类
  • 静态方法,没有默认的参数,就像函数一样

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

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

    @staticmethod
    def get_usr_pwd():   # 静态方法
        usr = input('用户名 :')
        pwd = input('密码 :')
        Login(usr,pwd)

Login.get_usr_pwd()
原文地址:https://www.cnblogs.com/wangyuxing/p/8318701.html