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

本文深入探讨Python的面向对象特性,包括类与实例的区别、类属性与实例属性的使用、类方法与静态方法的调用,特别是@classmethod和@staticmethod的实践。详细解析了@property属性的定义和应用,如只读属性和计算属性。此外,还介绍了单例模式的重要性和多种实现方式,如装饰器和new方法。最后进行了面向对象特性的总结。
摘要由CSDN通过智能技术生成

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.day = day

    def __str__(self):
        return "%s-%s-%d" % (self.year, self.month, self.day)

    @classmethod
    def today(cls):
        """
        返回当前的日期对象
        cls: 类名称Date
        :return: Date实例化的对象名称
        """
        # 获取当前的时间, 返回的是命名元组的格式
        # time.struct_time(tm_year=2019, tm_mon=12, tm_mday=29, tm_hour=16, tm_min=49, tm_sec=32, tm_wday=6, tm_yday=363, tm_isdst=0)
        now = time.localtime()
        return cls(now.tm_year, now.tm_mon, now
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值