Python3笔记036 - 7.2 类的定义

第7章 面向对象程序设计

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

7.2 类的定义

1、类的创建

在python中,要用class语句来创建类,class也是python中的关键字。

# 验证class是否为python的关键字
import keyword
print(keyword.iskeyword('class'))
output:
True

定义类的语法格式

class ClassName():
    '''类的帮助信息'''
    statement
    
参数说明
以class开头,空格后加类名,类名比函数多了一个要求,就是首字母大写。冒号表示类名定义结束。
类名后的括号,无继承时去掉括号,要不然会提示"remove redundant parentheses"删除多余的括号。
ClassName:类名,开头字母大写,一般采用驼峰式命名法
statement:类体,主要由类属性、类方法组成

# 定义一个最简单的类
class Book(object):
    pass

2、创建类的属性

类的属性是指在类中定义的变量,即属性,根据定义位置,可以分为类属性和实例属性

类属性,是指定义在类中,并且在方法体外的属性。可以通过类名或者实例名访问。

# 定义一个带有属性的类
class Book(object):
    title = 'python3' # title为类属性
    price = 50

3、创建类的方法

类的成员主要由类的属性和方法组成。创建类的成员后,可以通过类的实例访问它们。

# 定义一个带有类方法的类
class Book(object):
    title = 'python3'  # title为类属性
    price = 50

    def printprice(self, num): # printprice为类方法
        print(self.title + ':', num, '册' + self.price * num, '元')

4、创建__init__方法

在创建类后,系统会自动创建一个__init__方法,每当创建一个类的实例时,python都会自动执行它。也可以手动创建一个__init__方法。

class Rectangle():

    def __init__(self, a, b):

        self.a = a
        self.b = b

    def getPeri(self):
        peri = (self.a + self.b) * 2
        return peri

    def getArea(self):
        area = self.a * self.b
        return area


rect = Rectangle(3, 4)

print(rect.getPeri())

print(rect.getArea())

print(rect.__dict__)

__init__方法的第一参数必须是self,然后逗号分隔其它参数。

# 拓展:查看对象拥有的所有方法
# 定义一个带有类属性的类
class Book(object):
    title = 'python3'  # title为类属性,python3为属性值
    price = 50

    def printprice(self, num):
        print(self.title + ':', num, '册' + self.price * num, '元')


book1 = Book()
print(dir(book1))
output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'price', 'printprice', 'title']
posted @ 2020-07-20 08:17  测试工匠麻辣烫  阅读(228)  评论(0编辑  收藏  举报