python绑定与非绑定

一. 绑定

绑定分为两种:一种是对象绑定,一种是类绑定

对象绑定

对象绑定就是我们最常见的self绑定,其中self指向的是对象本身

class User:
    
    def __init__(self):
        self.money = 1000
        self.gender = '男'
        
    def func(self):
        print(f'性别:{self.gender},余额{self.money}')
# 每实例化一个对象,self就指向那个对象        
hz = User()

类绑定

类绑定是在类中写一个方法,该方法操作的一定是类属性,不是对象属性。因为类方法无法通过self去查询对象绑定的实例属性。
类方法,通过装饰器@classmethod进行装饰,绑定类属性cls,对类属性进行操作
@classmethod

class User:
    # 定义一个类属性
    count_id = 0

    def __init__(self):
        self.money = 1000
        self.gender = '男'
        self.class_method() # 把类方法放在init中,会在实例化对象的过程中自动调用

    def func(self):
        print(f'性别:{self.gender},余额{self.money}')

    # 定义类方法,绑定类属性,并操作类属性
    @classmethod
    def class_method(cls):
        cls.count_id += 1
        return cls.count_id
hz = User()
xc = User()
hh = User()
print(User.count_id)

调用类方法的两种方法

1.    类名.类方法名()
2.   对象名.类方法名()
class User:
    # 定义一个类属性
    count_id = 0

    def __init__(self):
        self.money = 1000
        self.gender = '男'
        self.class_method() # 把类方法放在init中,会在实例化对象的过程中自动调用

    def func(self):
        print(f'性别:{self.gender},余额{self.money}')

    # 定义类方法,绑定类属性,并操作类属性
    @classmethod
    def class_method(cls):
        cls.count_id += 1
        return cls.count_id

hz = User()
# 通过类名调用
print(User.class_method())
# 通过对象名调用
print(hz.class_method())

二.非绑定

静态方法,通过装饰器@staticmethod进行装饰
作用:把类外面的某一个功能函数或模块功能统一放到类中进行管理。方便代码的统一管理
注:静态方法是操作不了类中的所有东西
@staticmethod

import time
class User:
    # 定义一个类属性
    count_id = 0

    def __init__(self):
        self.money = 1000
        self.gender = '男'

    def func(self):
        print(f'性别:{self.gender},余额{self.money}')

    # 定义类方法,绑定类属性,并操作类属性
    @staticmethod
    def str_time(): # 括号中无任何绑定
        print(f'现在的时间是{time.strftime("%Y-%m-%d %H:%M:%S")}')


hz = User()
# 通过类名调用
User.str_time()
# 通过对象名调用
hz.str_time()

调用静态方法的两种方法

1.类名.静态方法名()
2.对象名.静态方法名()
import time
class User:
    # 定义一个类属性
    count_id = 0

    def __init__(self):
        self.money = 1000
        self.gender = '男'

    def func(self):
        print(f'性别:{self.gender},余额{self.money}')

    # 定义类方法,绑定类属性,并操作类属性
    @staticmethod
    def str_time(): # 括号中无任何绑定
        print(f'现在的时间是{time.strftime("%Y-%m-%d %H:%M:%S")}')


hz = User()
# 通过类名调用
User.str_time()
# 通过对象名调用
hz.str_time()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

^~^前行者~~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值