zoukankan      html  css  js  c++  java
  • Python3笔记037

    第7章 面向对象程序设计

    • 7.1 面向对象概述
    • 7.2 类的定义
    • 7.3 类的实例化
    • 7.4 访问限制
    • 7.5 继承
    • 7.6 封装
    • 7.7 多态
    • 7.8 装饰器
    • 7.9 特殊方法

    7.3 类的实例化

    类的实例化语法格式:

    obj = ClassName(parameterlist)
    参数说明
    ClassName:类名
    parameterlist:可选参数
    obj:对象名,即实例名
    

    类的实例化

    # 定义类,只有类属性,没有类方法
    class Book(object):
        pass
    book1 = Book()
    print(book1)
    output:
    <__main__.Book object at 0x000001C838838CC8>
    

    实例化后访问类属性

    # 定义类,只有类属性,没有类方法
    class Book(object):
        title = 'python3'
        price = 50
    
    
    # 实例化
    obj = Book()
    print(obj)
    print(obj.title)
    output:
    <__main__.Book object at 0x000001EFC64B8D08>
    python3
    

    实例化后访问类方法

    # 定义类,既有类属性又有类方法
    class Book(object):
        title = 'python3'  # title为类属性
        price = 50
    
        def computeprice(self, num): # printprice为类方法
            totalprice = str(self.price * num)
            print(self.title + ':', num, '册 ' + totalprice, '元')
    
    
    book1 = Book()
    book1.computeprice(2)
    output:
    python3: 2 册 100 元
    

    实例属性,是指定义在类的方法中的属性,只作用于当前实例中。只能通过实例名访问。

    实例化后访问实例属性

    # 实例属性:实例属性在__init__中定义,是实例化后对象的属性,通过对象名.属性名访问,而类属性通过类名.属性名访问
    class Rectangle(): # 定义类
        length = 1  # 类属性
        width = 1
    
        def __init__(self, length, width): # 构造方法
            self.length = length  # 实例属性
            self.width = width
    
        def getPeri(self): # 类方法
            peri = (self.length + self.width) * 2
            return peri # 方法返回值
    
        def getArea(self): # 类方法
            area = self.length * self.width
            return area
    
    
    rect = Rectangle(3, 4)  # 实例化
    # 访问实例属性、类属性
    print(Rectangle.length, Rectangle.width)  # 类名.属性名
    print(rect.length, rect.width)  # 对象名.属性名
    output:
    1 1
    3 4
    # 拓展:对象是否有这个属性
    print(hasattr(rect, 'length'))
    print(hasattr(rect, 'width'))
    output:
    True
    True
    # 拓展:判断对象object是否为类class的实例
    print(isinstance(rect,Rectangle))
    output:
    True
    
  • 相关阅读:
    [ISSUE]SyntaxWarning: name 'xxx' is assigned to before global declaration
    memcached 安装
    gulp 初体验
    gitcafe 使用hexo搭建博客
    sulime-text 3 安装以及使用
    media queries 媒体查询使用
    css3之@font-face---再也不用被迫使用web安全字体了
    前端的一些疑问总结01
    bootstrap 笔记01
    自定义表单样式之checkbox和radio
  • 原文地址:https://www.cnblogs.com/infuture/p/13343179.html
Copyright © 2011-2022 走看看