类方法、静态方法、属性

类方法:

@classmethod

添加classmethod的方法,即类方法,无法访问实例中的变量。
例:

class Animal(object):
    def __init__(self, name):
        self.name = name
    @classmethod
    def talk(self):
        print('%s is talking...' % self.name)

d = Animal('Ivien')
d.talk()

# Traceback (most recent call last):
#   File "D:/python/oldboy/DAY07/CPRAC.py", line 11, in <module>
#     d.talk()
#   File "D:/python/oldboy/DAY07/CPRAC.py", line 7, in talk
#     print('%s is talking...' % self.name)
# AttributeError: type object 'Animal' has no attribute 'name'
#
# Process finished with exit code 1

静态方法

@staticmethod

添加了@staticmethod的方法为静态方法,既无法访问类变量也无法访问实例变量。
例:

class Animal(object):
    def __init__(self, name):
        self.name = name
    @staticmethod
    def walk(self):
        print('%s is walking ...' % self.name)

d = Animal('Ivien')
d.walk()

# Traceback (most recent call last):
#   File "D:/python/oldboy/DAY07/CPRAC.py", line 9, in <module>
#     d.walk()
# TypeError: walk() missing 1 required positional argument: 'self'

属性

    @property

将方法转换为属性
例:


class Animal(object):
    def __init__(self, name):
        self.name = name

    animal_number = 9

    @property
    def count(self):
        print('There are %s ' % Animal.animal_number)

    @count.setter
    def count(self, ani_num):
        Animal.animal_number = ani_num
        print('ani_num :', Animal.animal_number)

    @count.deleter
    def count(self):
        del Animal.animal_number
        print('animal_number deleted')


d = Animal('Ivien')
d.count
d.count = 3
d.count

del d.count
# There are 9
# ani_num : 3
# There are 3
# animal_number deleted
print(d.count)

# Traceback (most recent call last):
#   File "D:/python/oldboy/DAY07/CPRAC.py", line 28, in <module>
#     print(d.count)
#   File "D:/python/oldboy/DAY07/CPRAC.py", line 9, in count
#     print('There are %s ' % Animal.animal_number)
# AttributeError: type object 'Animal' has no attribute 'animal_number'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值