python 面向对象高级特性----类与实例 & 类属性与实例属性 & 类方法与静态方法 & @property属性 & 单利模式

python 面向对象高级特性

一、类与实例

1.类属性和实例属性

1). 类属性不管有多少个对象, 都只存储一份。
实例属性存储的个数取决于实例的个数.
2). 作用域不同:
类属性: 通过类名/对象名来访问
实例属性: 只能通过对象名来访问。

import random
class Turtle(object):
    # power是类属性。
    power = 100
    def __init__(self):
        # x,y:实例属性.
        self.x = random.randint(0, 10)
        self.y = random.randint(0, 10)
# 1). 类属性不管有多少个对象, 都只存储一份。 实例属性存储的个数取决于实例的个数.
# 2). 作用域不同:
#		类属性: 通过类名/对象名来访问
#		实例属性: 只能通过对象名来访问。
print(Turtle.power)
turtle1 = Turtle()
print(turtle1.power, turtle1.x, turtle1.y)

二、类方法和静态方法

1). @classmethod: 类方法
2). @staticmethod:静态方法

类方法能够通过实例对象和类对象去访问。
静态方法能够通过实例对象和类对象去访问。

1. @classmethod: 类方法

类方法是类对象所拥有的方法,需要用修饰器一般以@classmethod来标识其为类方法,
1). 对于类方法,第一个参数必须是类对象,作为第一个参数 (cls是形参, 可以修改为其它变量名,但最好用’cls’了)
2). 能够通过实例对象和类对象去访问

2. @staticmethod:静态方法

静态方法需要用修饰器一般以@staticmethod来标识其为静态方法,
1). 静态方法不需要多定义参数
2). 能够通过实例对象和类对象去访问


1). @classmethod: 类方法
2). @staticmethod:静态方法
"""

import random
class Turtle(object):
    def __init__(self):
        # x,y:实例属性.
        self.x = random.randint(0, 10)
        self.y = random.randint(0, 10)
        self.power = 100

    # 默认情况下, Python解释器会自动将对象传递给类里面定义的方法。
    def eat(self):
        print("self: ", self)
        self.power += 20
    @classmethod
    def cls_example(cls):
        print("cls: ", cls)

    @staticmethod
    def static_example():
        print("静态方法.......")
turtle = Turtle()
turtle.eat()
turtle.cls_example()
turtle.static_example()
# 类方法能够通过实例对象和类对象去访问。
Turtle.cls_example()
# 静态方法能够通过实例对象和类对象去访问。
Turtle.static_example()


3.类方法和静态方法的应用


import time

"""
# 系统自带date类的使用
from datetime import date

dateObj = date(2019, 10, 10)
print(dateObj)
print(date.today())
"""

class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.da
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
装饰器(decorator)是一种可以给函数或动态添加功能的工具。在Python中,有一些内置的装饰器,比如@staticmethod、@classmethod和@property。 @staticmethod装饰器用于定义静态方法静态方法是一个和没有绑定关系的方法,可以直接通过名调用,也可以通过实例调用。使用@staticmethod装饰器可以将一个方法转变为静态方法。 @classmethod装饰器用于定义方法方法是与相关联的方法,通过名调用时,会将本身作为第一个参数传入。使用@classmethod装饰器可以将一个方法转变为方法。 @property装饰器用于定义属性属性是一种特殊的方法,可以像访问属性一样来访问方法。使用@property装饰器可以将一个方法转变为属性。通常,一个@property装饰器会配合一个相应的.setter装饰器使用,来定义属性的设置方法。 举个例子,对于一个名为Student的: class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value 这个中的score方法被@property装饰器修饰,使得它可以像属性一样被访问。同时,@score.setter装饰器定义了一个setter方法,用于设置score属性的值。这样,我们可以通过实例的score属性来获取和设置学生的成绩。 总结起来,@staticmethod、@classmethod和@propertyPython内置的装饰器,分别用于定义静态方法方法属性。它们可以让我们的代码更加简洁和易读。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python面试常问的几个内置装饰器:@staticmethod、@classmethod和@property](https://blog.csdn.net/weixin_35383324/article/details/113674252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python 使用@property属性进行数据规范性校验](https://blog.csdn.net/a772304419/article/details/120813610)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值