
Object Oriented Programming
- procedure-oriented: we design program around function,blocks of statements which manipulate data.
object-oriented:We organize program which is to combine data and functionality and wrap it inside something called an object - Two main aspect: classes and objects
A class creats a new type where objects are instances of the class - fields:Variable that belong to an object or class are referred to as fields
method:Objects can have functionality by using functions that belong to a class.Such functions are called methods of the class - Fileds are of two types-They can belong to each instance/object of the class or they can belong to the class itself.They are called instance variable or class variable
- A class is created using the
classkeyword.The fields and methods of the class are listed in an indented block. - Class method have only one specific difference from ordinary function-they must have an extra first name that has to be added to the beginning of the parameter list,but you don’t give a value for this parameter when you call the method,Python will provide it.This particular variable refers to the object itself,and by convention,it is given the name ‘self’
- Example:
1
2
3
4
5
6class Person:
def say_hi(self):
print('Hello World')
p=Person()
p.say_hi()
- Notice that the
say_hi()method takes no parameters but still has theselfin the function definition
-
init method:This method is run as soon as an object of a class is created,which is useful to do any initialization.
1
2
3
4
5
6
7
8class Person:
def __init__(self,name):
self.name=name
def say_hi(self):
print('Hello,',self.name)
p=Person('Tom')
p.say_hi() -
Class and Object Variation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43class Robot:
"""Represent a robot,with a name."""
#A class varible,counting the number of robots
population=0
def __init__(self,name):
"""Initializes the data."""
self.name=name
print("(Initializing {}).".format(self.name))
#When this person is created,the robot adds to the population
Robot.population+=1
def die(self):
"""I'm dying"""
print("{} is being destroyed!".format(self.name))
Robot.population-=1
if Robot.population==0:
print("{} was the last one.".format(self.name))
else:
print('There are still {:d} robots working'.format(Robot.population))
def say_hi(self):
"""greeting by robot.
Yeah,they can do that."""
print("Greeting,my masters call me {}.".format(self.name))
@classmethod
def how_many(cls):
"""print the current population."""
print('We have {:d} robots'.format(cls.population))
droid1=Robot('R2-D2')
droid1.say_hi()
droid1.how_many()#????
Robot.how_many()#droid1 and Robot both?
droid2=Robot('R3-D3')
droid2.say_hi()
Robot.how_many()
droid1.die()
droid2.die()
Robot.how_many()
- insead of
Robot.population,we could have also usedself.__class__.populationbecause every object refers to its class via theself.__class__attribute - we have marked the
how_manymethod as a classmethod using adecorator,@classmethod,which is the same as callinghow_many=classmethod(how_many)
Inheritance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39class schoolMember:
"""represent any school member"""
def __init__(self,name,age):
self.name=name
self.age=age
print('Initialized schoolMember:{}'.format(self.name))
def tell(self):
"""Tell my details"""
print('Name:"{}" Age:"{}"'.format(self.name,self.age),end='')
class Teacher(schoolMember):
"""Represent a teacher"""
def __init__(self,name,age,salary):
schoolMember.__init__(self,name,age)
self.salary=salary
print('(Initialized Teacher:{})'.format(self.name))
def tell(self):
schoolMember.tell(self)
print('Salary:"{:d}"'.format(self.salary))
class Student(schoolMember):
"""Represent a student"""
def __init__(self,name,age,marks):
schoolMember.__init__(self,name,age)
self.marks=marks
print("(Initialized Student:{})".format(self.name))
def tell(self):
schoolMember.tell(self)
print('Marks:"{:d}"'.format(self.marks))
t=Teacher('Tom',40,30000)
s=Student('Jim',10,80)
print()
members=[t,s]
for x in members:
x.tell()
output:
1 |
[email protected]:~/Python$ python3 heritance.py |
- Since we are defining a init method in
TeacherandStudentsubclasses,Python does not automatically call the constructor of the base classschoolMember,you have to explicitly call it yourself.In contrast,if we have not defined an init method in a subclass.Python will call the constructor of the base class automatically. - Python always starts looking at the method in the actual subclass type first,and if it doesn’t find anything,it starts looking at the method in subclass’s base classes,one by one in the order.




近期评论