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