zoukankan      html  css  js  c++  java
  • 面向对象知识点2

    类中@property的使用

    ​ Python 内置的@property 装饰器就是负责把一个方法变成属性调用的:既能检查参数,又可以用类似属性这样简单的方式来访问类的变量。

    ​ property属性的定义和调用要注意一下几点:

    1. 定义时,在实例方法的基础上添加 @property 装饰器;并且仅有一个self参数
    2. 调用时,无需括号
    #计算圆的面积和周长
    from math import pi
    
    class Circle:
        def __init__(self,radius):
            self.radius = radius
            
        @property
        def area(self):
            return pi*self.radius**2
        
        @property
        def perimeter(self):
            return 2*pi*self.radius
    
    c = Circle(8)
    print(c.area)   #201.06192982974676
    print(c.perimeter)  #50.26548245743669
    

    类与对象的绑定方法与非绑定方法

    class Foo:
    
        # 绑定给对象的方法:只有对象能用;但是类也能用,使用的时候必须得传参
        def f1(self):
            print(self)
    
        #绑定给类的方法:被装饰函数给类使用,约定俗成参数为cls;对象也可以使用,但参数依旧是类
        @classmethod
        def f2(cls):
            print(cls)
        
        #非绑定的方法:相当于定义了普通的函数,供类和对象共同使用
        @staticmethod
        def f3(self):
            print(self)
       
    

    ​ 什么时候使用?

    	这个方法需要使用类做为参数的时候就得使用类绑定方法,@classmethod
    	这个方法需要使用对象作为参数的时候就得使用对象绑定方法
    	 这方法即不需要类作为参数又不需要对象作为参数,使用非绑定方法,@staticmethod
    
    #@classmethod用法:绑定给类
    class Operate_dtabase:
        host = '192.168.1.5'
        port = '3306'
        user = 'wq'
        pwd = '12345'
        @classmethod
        def connect(cls):
            print(cls.host)
    
    #通过类调用
    Operate_dtabase.connect()	#192.168.1.5
    
    #通过对象调用
    f = Operate_dtabase()
    f.connect()					#192.168.1.5
    
    
    #staticmethod用法:非绑定
    import hmac
    
    class Operate_database:
        def __init__(self,password):
            self.password = password
    
        @staticmethod
        def get_password(salt,password):
            m = hmac.new(b'salt')
            m.update(b'self.password')
            return m.hexdigest()
    
    #通过类调用
    hmac_password = Operate_database.get_password('wq',123)
    print(hmac_password)import hmac
    
    class Operate_database:
        def __init__(self,password):
            self.password = password
    
        @staticmethod
        def get_password(salt,password):
            m = hmac.new(b'salt')
            m.update(b'self.password')
            return m.hexdigest()
    hmac_password = Operate_database.get_password('wq',123)
    print(hmac_password)	#05526cf35b676abc8b3416ddc17ce4ea
    
    p = Operate_database(123)
    hmac_password1 =p.get_password('wq',p.password)
    print(hmac_password1)	#05526cf35b676abc8b3416ddc17ce4ea
    
    
  • 相关阅读:
    module.export和export
    netty学习
    I/O知识
    cxf+spring+数字签名开发webservice(二)
    cxf+spring+数字签名开发webservice(一)
    js作用域
    js继承
    js模块和级联
    python全栈_011_Python3基本数据类型--字典
    python全栈_010_Python3基本数据类型--元组
  • 原文地址:https://www.cnblogs.com/bruce123/p/11074655.html
Copyright © 2011-2022 走看看