Python - Class and Subclass 学习笔记
- Class
- Class 和 Object 的 Folder
- The Class Definition
- Constructor and Initializer
- Instances and Attributes
- Hidden Attribute and Data Encapsulation
- Method
- Hiding Methods From Access
- Operator Overloading
- Subclasses
- Subclass 的 Folder
- Subclass
- Bottom-Up Rule
- Accessing Superclass Method
- About super()
- Application in Initializer
Class 定义:A class is any type that is not built-in to Python. A value of this type is called object.
Class 和 Object 的 Folder 上方为object的folder (其中id number是object的地址),下方为class的folder,both folder are stored in heap space.
文章图片
<object>.<name> 代表:
- 到object的folder中找attribute/method name
- If missing, check Class Folder
- If not in either, raise Error
The Class Definition 定义:a blueprint for the objects of the class. A class defines the components of each object of the class. All objects of the class have the same components, meaning they have the same attributes and methods. The only difference between objects is the values of their attributes.
class ():
"class specification"
Constructor and Initializer Constructor 定义: a function that creates a object for a class. It puts the object in heap space, and returns the name of the object (folder name) so you can store variable / attribute in it.
constructor 默认没有任何argument。生成一个empty folder。
特点:
- constructor 的 name 与 type of the object 一样(即class name)其中,instance is initially empty
- 创建一个 empty object folder
- It puts the folder into heap space
- 执行 initializer method __ init __() (defined in the body of the class)
- 当__ init __() 执行完毕,返回object(folder)name as final value of expression. (没有return statement)
- Passes the folder name to that parameter self
- Passes the other argument in order
- Executes the commands in the body of __ init __()
例:
class A(object):
z = 5def __init__(self,x)
self.x = x + self.zclass B(A):
z = 10def __init__(self,x,y):
super().__init__(x)
self.y = y def down(self):
shift = self.x - self.z
return A(shift)
当我们执行
>>> b = B(2,3)
>>> c = b.down()
时,方法down()最后一步return会产生一个新的empty folder,其type是A。所以,假设b对应的folder是id2(B),则return的folder将会是id3(A)
Default Argument
python不像java可以写很多constructor对应不同argument。
def __init__(self, x=0, y=0, z=0)
self.x = x
self.y = y
self.z = z
若没有给x,y,z的值,则取默认的value,否则覆盖默认的值,并在object folder中添加相应值的attribute。
Instances and Attributes Assignments add object attribute:
<object>. <attribute> = <expression>
Assignments add class attribute:
<object>. <attribute> = <expression>
object can access class attributes,若对象和类中都有一样的attribute,check object first.
(Bottom-Up Rule: It first looks in the object folder. If it cannot find it there, it moves to the class folder for this object. It then follows the arrows from child class to parent class until it finds it. If Python reaches the folder for object (the super class of all) and still cannot find it, it raises an error.)
Hidden Attribute and Data Encapsulation
- Underscore makes attribute hidden (例,_red ; _minute)
- Do not use outside of class
例子:
class Time(object):def getHour(self):
"""Return: hour attribute"""
return self._hourdef setHour(self, h):
""" Sets hour to h
Precondition: h is an int in 0..23"""
assert type(h) == int
assert 0 <= h and h < 24
self._hour = h
Mutable Attribute: has both getter and setter
Immutable Attribute: has only getter but no setter
Method 定义:Methods are functions that are stored inside of an class folder. (对比:attribute存储在object folder中) They are indented inside-of a class definition.
Function Call:
()Method Call:
.
The object before the dot is passed to the method definition as the argument self, 所以任何method definition都有至少一个parameter。
class Point3(object):
"""Instances are points in 3d space
x: x coord [float]
y: y coord [float]
z: z coord [float] """def distance(self,q):
"""Returns: dist from self to q
Precondition: q a Point3"""assert type(q) == Point3
sqrdst = ((self.x-q.x)**2 + (self.y-q.y)**2 + (self.z-q.z)**2)
return math.sqrt(sqrdst)
Remark:
- Enforcing Precondition: When calling methods, ensure preconditions are true. (在每个method开头写assert-statement)
- Enforcing Invariant: If attributes are altered, ensure class invariant is true. (在setter中写assert-statement)
Put underscore in front of a method will make it hidden
- Will not show up in help()
- But it is still there…
例:def _is_minute(self,m):
例:
def __init__(self, hour, min):
"""The time hour:min. Pre: hour in 0..23;
min in 0..59"""
assert self._is_minute(m)
Operator Overloading 定义:The means by which Python evaluates the various operator symbols, such as +, *, /, and the like. The name refers to the fact that an operator can have many different “meanings” and the correct meaning depends on the type of the objects involved.
其中:
__ add __ corresponds to +
__ mul __ corresponds to *
__ eq __ corresponds to ==
def __str__(self):
""" Return : string with content"""
return '('+self.x + ',' + self.y + ',' + self.z + ')
Subclasses Subclass 的 Folder
文章图片
Subclass Subclass 定义:A subclass B is a class that extends another class C. This means that an instance of D inherits all the attributes and methods that an instance of C has, in addition to the one declared in D. (也会继承隐藏方法和attribute,但是access都用getter和setter)
Bottom-Up Rule
To Look Up Attribute / Method Name:
- Look first in instance (object folder)
- Then look in the classThen look in the class (folder)
- Look in the superclass
- Repeat 3 until reach object
![http://www.cs.cornell.edu/courses/cs1110/2018fa/lectures/10-30-18/presentation-19.pdf]](https://img-blog.csdnimg.cn/2018110403121925.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzE5Mjk4Mw==,size_16,color_FFFFFF,t_70)
例:
Accessing Superclass Method Use Function super():
super().__str__()
子类和父类的代码:
class Employee(object):
def __str__(self):
return(self._name + ', year ' + str(self._start) + ', salary '
+ str(self._salary))class Executive(Employee):
def __str__(self):
return (super().__str__() + ', bonus ' + str(self._bonus) )
注:在python2.7中super(self).__ str __()
About super()
若一个子类上有很多父类,不能写成super().super()。可以写成super(class, self),其中class是subclass,self是object in method
文章图片
Application in Initializer attribute初始化的继承的写法:
class Employee(object):
def __init__(self, n, d, s=50000.0):
self._name = n
self._start = d
self._salary = sclass Executive(Employee):
def __init__(self, n, d, b = 0.0):
super().__init__(n,d)
self._bonus = b
【Python - Class and Subclass 学习笔记】产生的folder如下:
文章图片
推荐阅读
- 学习笔记|uni-app开发小程序
- java计算文本MD5值
- Android圆形进度条控件-CircleSeekBar
- 学习笔记|安卓中一些界面过场动画的实现
- MongoDB-存储
- 学习笔记|Burnside引理和polay计数学习笔记
- Python|【网易2019年秋招笔试题】编程题第二题(香槟塔里倒香槟——参考代码和编程思路)
- Android|安装APP损坏,出现[INSTALL_FAILED_DEXOPT]的解决办法
- Android|java日期格式化
- Android|android 读取json数据(遍历JSONObject和JSONArray