定义:A class is any type that is not built-in to Python. A value of this type is called object.
上方为object的folder (其中id number是object的地址),下方为class的folder,both folder are stored in heap space.
<object>.<name> 代表:
class folder 内会存储:Data common to all objects
定义: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 定义: 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。
特点:
在执行__ init __(self, … ) 的过程中:
只要生成一个新的object,就会在这一步生成一个empty folder
例:
class A(object):
z = 5
def __init__(self,x)
self.x = x + self.z
class B(A):
z = 10
def __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。
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.)
此时,我们需要getter and setter to change and to access attributes
例子:
class Time(object):
def getHour(self):
"""Return: hour attribute"""
return self._hour
def 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
定义: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:
Put underscore in front of a method will make it hidden
def _is_minute(self,m):
一般hiding methods被用作为helper method
例:
def __init__(self, hour, min):
"""The time hour:min. Pre: hour in 0..23; min in 0..59"""
assert self._is_minute(m)
定义: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 + ')
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)
To Look Up Attribute / Method Name:
This also works for Class Attribute
![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)
例:
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 __()
若一个子类上有很多父类,不能写成super().super()。可以写成super(class, self),其中class是subclass,self是object in method
attribute初始化的继承的写法:
class Employee(object):
def __init__(self, n, d, s=50000.0):
self._name = n
self._start = d
self._salary = s
class Executive(Employee):
def __init__(self, n, d, b = 0.0):
super().__init__(n,d)
self._bonus = b