Python3学习笔记6-类,面向对象编程

124 篇文章 0 订阅

1 类
类一般都和面向对象编程在一起出现。
Classes and Object-oriented programming
⑴ Class can be used in many different ways. In this book we emphasize using them in the context of object-oriented programming.The key to object-oriented programming id thinking about objects as collections of both data and the functions that operate on that data.
⑵ In python, one implements data abstractions using classes.
⑶ A class definition creates an object of type type and associates with that object a set of objects of type instance method.
⑷ When a function definition occurs within a class definition, the defined function is called a method and is associated with the class. These methods are sometimes referred to as method attributes of the class.
<摘自John V. Guttag,Introduction to Computation and Programming Using Python, Spring 2013 Edition>

下面是一个简单的类,有类的定义,实例化,hasattar()等函数的使用。
class关键词和类名之后,使用了init 函数对Student进行初始化,同时需要传递两个参数:name 和 age。
传递的参数在类中变成了self 的属性,类创建完成后,使用了me = Student(“FengWeilei”,22) 来实例化。这时候,me是一个Student类,或者说是一个对象。me有着两个属性,对应着”FengWeilei”和 22 两个参数。

class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age


>>> me = Student("FengWeilei",22)  #Instantiation
>>> hasattr(me,'name')
True
>>> hasattr(me,'gender')
False
>>> getattr(me,'age')
22
>>> setattr(me,'gender','male')
>>> hasattr(me,'gender')
True
>>> 
>>> 
>>> me.age  #Attribute reference
22
>>> delattr(me,'age')
>>> hasattr(me,'age')
False
>>> 

2 Inheritance

What is Inheritance?
Inheritance is used to indicate that one class will get most or all of its features from a parent class. This happens implicitly whenever you write class Foo(Bar), which says “Make a class Foo that inherits from Bar.” When you do this, the language makes any action that you do on instances of Foo also work as if they were done to an instance of Bar. Doing this lets you put common functionality in the Bar class, then specialize that functionality in the Foo class as needed.

来自 https://learnpythonthehardway.org/book/ex44.html

类的实例化经常能见到。
看flask文档。最开始就有

from flask import Flask #从flask模块中导入Flask类

app = Flask(__name__) # Flask类的实例化,这时的 app 成了一个对象

app.run() # app 拥有着Flask类中的方法,用.来调用run() 方法。

一直没有遇到需要继承类的时候,需要用到了再深入了解一下。
https://docs.python.org/3/tutorial/classes.html#inheritance

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值